diff --git a/.gitignore b/.gitignore index 8b1e6e9d..9e37a517 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +*_p* + build/ *.class *.out @@ -398,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/Dockerfile b/Dockerfile new file mode 100644 index 00000000..e8f90b36 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,3 @@ +FROM nginx +EXPOSE 80 +COPY build/html/ /usr/share/nginx/html/ 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 61e957f9..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,11 +26,18 @@ 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)/* +deploy: + python3 -m venv --copies deploy + . deploy/bin/activate + pip install -r source/requirements.txt + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @@ -104,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 3087326e..00000000 --- a/README.rst +++ /dev/null @@ -1,41 +0,0 @@ -https://www.learntosolveit.com -============================== - -This is the main site with all the source code snippets and documentation. - - -.. image:: https://readthedocs.org/projects/learntosolveit/badge/?version=latest - :target: https://www.learntosolveit.com/?badge=latest - :alt: Documentation Status - - -directives used ---------------- - -For the Run This link. - -:: - - .. runcode:: /path/to/code - :language: c, python, java, scala, ruby, go - :codesite: ideone - -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/ -* https://github.com/uthcode/sphinxcontrib-runcode/ -* https://github.com/ryan-roemer/sphinx-bootstrap-theme - -Contact -------- - -* Senthil Kumaran diff --git a/codemap.json b/codemap.json deleted file mode 100644 index 72bb78d5..00000000 --- a/codemap.json +++ /dev/null @@ -1 +0,0 @@ -{"00d9d9cdc121c2f7f4b67ae122308450": "aDBGYq", "00e2143bcb14fa5e5e0479904b778db9": "aXM3ST", "011ce23615f2cbb2e40ec049b86fd414": "QDDk5D", "01417b8700205169be6bd5839040f3f7": "sOyGvw", "0206f322c57ff87e317c221593f199c9": "nFqdZD", "0252b4bc0140be29d08a52f8a3606710": "6ui0jo", "033b50318b863b14465d794ba2e5bc6d": "LR2pFr", "034018f099da9ae1507c8f6955a42ab4": "0DWFgP", "03c81db672b2f8db5de0342d7ee747ab": "xkPjys", "0404c78249e0692f44214defa47badb7": "PUuaCX", "0484eff635813dac3d09afc919a20099": "ovriMQ", "06a6d73a06af5b4cd6eaf88f55d7d1dc": "fZNNnK", "075ce59a6adfb46727a9c69cafbbdec9": "r3mJgs", "07702eee92157018f31a3bf61654c543": "3W4gWU", "077dd12e53418ec30b5c652c50f5787f": "CicxEL", "07c35588475f76ce76006d6318ab2a3a": "oya0gC", "080f627bc6a1323d2b540d71c2f03cf5": "bR3UfD", "084b56fe2a86766d54a3e0198b701398": "ZLgaf4", "08ac99d79931e980f09b1b394b9a4991": "urtzXU", "0937cfc1a3dbc7faf6b0e0f99c22aca0": "v8Lo9N", "0953ce257a302dcd416ec5863d155220": "wgABjz", "098972249d9f1524f2bd11e7294d6d13": "k9Aebi", "098b317fe4ccf65d2c672b66b9e4916f": "tcCvg0", "09b0f5ebafcf85d22e88a1a5395935a0": "WkTGHo", "0b15423ee2f2cb64568dbd0fd6936ef4": "pRiYh5", "0b44e2a69fb5df650dfc5b54882a4cbf": "Y02Tql", "0b778a122070b27d5aa1df82e77cd335": "9Hs8E1", "0bd35d42f866eb4303b964c4102c8618": "hHdUip", "0c305fb3a137cbb3993e31899c596ab1": "kzJUpB", "0e0463d7c3693281bc10974bfc701bc8": "TLwsaK", "0e76a9780e4c7d1c30b8d192d6cb24f3": "yo7AEP", "0ef995489aa90a37c61e7d362db036e2": "f1l5nb", "0ff3e9b9557f802b767ba444e40bc175": "un1HZO", "119b02fd9cb186543829ea38b34909e5": "mvHxN7", "11ffa5cd695d9f65fce27d1a6b8c0fc5": "4JwNbN", "12bff77baa280f72b970cb5e6e07b700": "IDbZLI", "13555674a9dfcc2ae3f5a16fffa1af67": "cjDMWs", "139b6abc6b769a10f887fc4f7f30f053": "34f7TL", "14a5d10bf24c44e83b4e1f685b1a2e19": "oH69o7", "14ca3dd32324a92e159273d7774cd6ee": "dClJCz", "17334eb0a50bc158d802c83178404b5b": "wRWDVx", "17373250864f980c96391bbdd88be750": "ziUjXd", "17598a4d09bd2743f29a800662ec8634": "uCYwq3", "18028e2b7b61968a46f7750021d8412e": "43jAcv", "1860221ae7e3f15f1be3aa489350fc07": "bUmX6l", "1a229303b65d87a72f373ef47a2b6ec7": "QeCj1O", "1a4ebf6c830fd2528089540bce01c338": "1HTlfO", "1a82372457fce9fcb509b82ebb19092b": "hbPpLm", "1a93bb1268c0331f372d1e44ac483f56": "yun1KR", "1ad2605209066a68e2d8d5bb5908feaf": "EWCkNc", "1b5968055b457bcc2969a1f41b35e302": "pUoPEb", "1c81871ecfe40d6f73f11b7fd45fcc53": "zRzXDB", "1cc801604d6d5dc8f7651ef44c613f9c": "9wrpFI", "1e1ede444eadcfae7aa74a1da515e64e": "0rSOYi", "1e3ddc2498772d3b550fb256bbd03fb8": "ATVhMn", "1e496d88444102fe39278f1fcf8ac9bb": "0s79UX", "1e5f5900085302c517d43fff5b7c7323": "Ypt9T5", "1ef0c7712bdf9d7c7733d873553942eb": "BmHnbf", "1f071f57f77a932fecb0cd031bbe0742": "2ybgGO", "1f3435f7a5f0ca164549e3c533d97bc9": "cvLlA8", "2089577f61fab993bd2522c8f17df81c": "X9zABA", "209342353fc00e716d2463b329b3b396": "oAdUqq", "20b0968faa19b6dc262eb0493b9f8714": "C37l7l", "21dfa21e40c9408c6db35e109b2070bf": "XqKshm", "21fcd0c84e156918f67495dc95a17d68": "uxmbbV", "22a5ccfe778affaef492e8ecb55eea8e": "hoxZEH", "22aac93d8d78277e707a02ef95386b29": "uSSU6K", "23042cb3bba139f05321ca9baac8d499": "wVJNtI", "23341178089a20316e428cccfea19c21": "ffvvjU", "23356ea8c84fdac932eefe08ce2a7902": "k6TcAh", "236d345c69b9e4efece2c3c43eaf4137": "H2olKN", "239f802081dcfe944637441465dbd886": "Ux5ZVD", "23fe4005d03ecc49db491a4d73c16db2": "W4uXAG", "247419a0b2407c3695214057c19d06c2": "QNeut1", "249a4f7265b622d96efde2f32f770e6c": "JMxU2u", "25378ca6c7e67e7cba53c07278ad537b": "fK5wi2", "255c9ff380bcd0cbac530057239f33f3": "PPSpym", "2564fb22c520ec9611c66e81cdbc1ce0": "rDyzRP", "25c590a8df4d8c5b97fc14df2e5d750d": "nAEcOx", "2652d48609af2d4be15be0bbab1a801b": "1IvWus", "26edb72e502ca0969fd537e07b60adca": "NJf7GV", "273b77bedf5843c150d03e4593475edf": "iD8TSU", "278c8bfcbf5c6679376a056c1d9f55d4": "4Xk9Mo", "290859c341d0ed3b29dd0d81f19cceef": "YAJepx", "29529f66349da287462c5e4e9dd858fc": "Q5Yi2e", "299145d539b47f8812a1ad50a8c4730b": "V3JRLX", "2a912c36809d1d702f7c331b2971ceb0": "MPjXuM", "2b3835049657ee39b614bd6246cf054b": "HTEQ1y", "2bae50a9a192e3ab52223bcede915b77": "CXeU56", "2bf0fbe99093221de899f3752fb2af5d": "hy1zSy", "2d1ac09803474845d3b277a473f56844": "BmyYcj", "2df033cd9adb67f3756b93be62eec2f8": "dULCrL", "2ea24ed1ae852e6359f0150b43311388": "DdYH0J", "2ef0a9eeb96a1cad4198e0fcbedc2c68": "jscj1W", "2f69479116a9e3b98e57db48aa0bbd37": "PLRed6", "2f72486673de4bfb73a7334721678be6": "swbQ6H", "2fb4b3ff6409860b9c2aef9a29f64691": "MP7W97", "2fbf35600698387d73f472d99fe8b212": "WvXpEm", "30256344195789053409d38ce8d9bc22": "3CA4al", "3192fdf5910cb18c7e502006519d7cdb": "a6N6a3", "31aafdf7f705fece7156270a9e639031": "yHA3WY", "31b513228b87a0e958eaf5528ad1a831": "GFEmcl", "32508a5e8f931e4d52c190c86b0df4fb": "wZ3WS3", "333a74e2b3dc14c9c51d8fb995c80904": "i5z4J2", "338a91b34a91b8c02d2f5c8fb40b8d8d": "Ytfpev", "345702dcf4aaf560d036d0e74e84e046": "xXVQkF", "34c065eea56bd6bb0e141ebe07cdf81d": "TPAJCf", "34e52a6379f63a62347ade5f6b9005dc": "QGwjhn", "34f277199fb48867873773f7b1112966": "PTqdv9", "3560228625ae5ab570e3cdd3541e02b8": "S3nCRy", "35899ec14d4615abe33b7574de6096d1": "mJB0g1", "36017fe3af5e53eab15dfa9382ca83cc": "UybmKm", "3618bb44b1ce7d975da881b0d49c732e": "TEZf9U", "36294cfccbd411c5e8c1fbf8ffcd54c7": "uCBIfp", "367ef8e10412ee18b39c7d2447f61b7f": "iloMDW", "36ab82be3eaea557a80d0e2567e727ee": "87TaJm", "3782eb41255b5a2f4290bfa54af5cee6": "qNReG4", "37a72b54aa06e71c540dc57f3ea730f1": "H3hDHK", "382afccb33a9f7b0105dee1a63cee11a": "JLIhIz", "38bee8826e7b363909bb89d233df1fa9": "i4MCAe", "3a60adf4f28da2d9bc8f153f0aa9964e": "y5VS8F", "3ac9fdc3560b18f11cb9f2d8948891bf": "vK6pUz", "3bb5f3425ff6bcd84d89fc62784027dc": "Efv3SV", "3bdbc85c56410c09c2e451e85165be30": "1nnQh8", "3bfce164123564e96ab6c93796cc42e7": "IjmB77", "3c618ccb055103370a6475da31fededb": "5eBBEs", "3c9adf90dbd0067c9069e2e238163ea0": "0a7kU5", "3d68f909c2e6e8547df1046eafd422e9": "zbRdCh", "3ea20b4ef4847f744de2fc12f044de57": "bgqFr8", "3fc2eeb85d854447560b00c126fbbbeb": "cWSWV7", "3fd8e2883a735a89152b1af03cfbef58": "JWpZZN", "405cf710e1de4310f9e25179f45e45c4": "Rh1C7m", "4082bd918da3718fbafa828fd5630b94": "9l37Ke", "40ffe11029d8bb0d39e10b90b6273fd1": "esoECv", "4129564a1c7b47b00ec0786993908120": "sJMmWm", "415371d3a57a055c8358619e638a8a9b": "8pA08a", "41af8d777f50b1f3b7e91ddd071dc709": "fCnOH6", "41b29708372aaa34ed318889e276fed7": "JYaK6b", "41b2fb98574cf6393373cd0c8a56f6a4": "itkwbP", "43529d2edd67fde1ddea712fb2d96993": "6RvXk3", "437ab06489449856f1e7e2fc615cf61c": "Ifi9gZ", "44d3b7b4c2e3c806995281590473c901": "onoEZX", "44e75a6370a71a4616136e955871b4ac": "sCtx00", "45642cba4f4b88fc7cc769b370686e18": "ByRK5C", "456a89c10f2071be14b355802701a183": "W0IEOx", "457c55b915658dde9cf41c43d4e430ac": "bXdea6", "460d039b63991a742baaafa48ff32634": "FSP6Ly", "461195f3b4e2ab020c15568218b3ef24": "ylUotq", "466c73c64e873a9804495d1ceaba0da3": "jmSVNu", "46b92265d670cd084c80c5f44ca59de7": "SPrNme", "46f601d3f0a9a9f7a35d405dd8b9bcc5": "1x9TaL", "477b47af995794138427f9313aa24104": "6mUMmL", "479b3cb97b8654b18943e0ef7933b71b": "6n3oSs", "4926a6f0e4606d663f7fef0c56566fcd": "1WMrfs", "49472d029cc8bc6a885ca03aabb14db8": "xBPBwX", "49ed263062580f5618eb1d3a2eedadf6": "JLG9Ez", "4a1c7f5cd85f3f2893b80110f0e50ef0": "3em37c", "4a595547d3ae1c110f9f8cec040ea9ae": "u81VoO", "4a5e1c127ae3e9de050cb882956493ed": "8tSek3", "4b092d10f594c3d5c0824acdcb839f55": "rnHRA1", "4b67d0368acabf3431ba3ac222b1ff85": "ujrDy2", "4ba2953ef46cf3384aca2a85ce049f5c": "zwvk68", "4c24e50204da109ff1fb1bba5c7125e8": "wX06Go", "4c72ff2827c307925dc3fb620b326b55": "4O7NsN", "4c7ea9a9d8d8e860baa0cb20a6f24fc0": "Mx0Ztt", "4cc9862f8b3e5d61781006d747d734ae": "bswLvv", "4d76af2dab4c75b1ff24bf7dfc72dbe4": "mSfWdp", "4dbec780db03ab7a876e27787494d59d": "eAfg4q", "4e16ffbeb01541acdfcc5d9ad9d24463": "mbRTPo", "4e7e856d7f497d19142bd271591b14b3": "AKQWpB", "4e9c00717acc4b54ea3b346c081d978b": "4XWz4c", "4fcbaf3639109ae48d4d5562d3dd1f79": "BS9lX0", "5097b6b431c3166131dac553ec155e36": "QORjTs", "50c799effb7410fb5e173627cbd009ff": "I6O4RU", "510b95b030f69ecd3875d090b77971c2": "kaxTJT", "518273c19df9f2f4a73db81115d84cd5": "9oZ545", "51db31c7a9f882a30190a8b11d977393": "kZNzIZ", "52198ac30e61c21b622a6255d8e3b556": "c5HMDH", "526933a4bec1b1fce8b7f338556a42c7": "xBSFYE", "53443cee1831850db5fcf17ad7011b66": "v1JIcO", "538725eaab346486698ffc7b71dbe1ff": "37yQLS", "53ac95ff2fbe7ca732d81ff1435e9fd6": "wUmwPm", "548a4b65370fe443cfe5da16010f6724": "QRFRka", "54b4f778d9a7e244b7345d9399bf40c9": "R2v9p2", "54f383324d156d346ffce552fa5368a0": "2djhgk", "569de57e656eef0823bad7aa951a3ad1": "s3tdtA", "56fa41d3251032cf413747a1c04bf52d": "T1ycP5", "56fc8fbd97526d48a1c58d1c8d4cc0a7": "D6kxZe", "57ca6231995c1d536a3d7883aaff1b41": "BFKNEZ", "57cc554c9e06adf00046e29b792138b8": "ZD7gLK", "581bd2b52aac85518095a3e2ff1fbc89": "0YU5uJ", "5822e35b1e2ea0510e81aa2e4a31250c": "bAyqjK", "58f71545eba5cff6b08e9af44d4f48f6": "bb0PyH", "59a763fe97d6711b44ff8dbce12725e0": "hwyuAW", "59ccc9587dd36be7fa6e89142e1bd585": "666X1e", "59e50e91942a9a8cb1a4f16fd014df7f": "Oit7gp", "5a33c52bab689a057edd063c15834e74": "LDpYcO", "5bf5d848152230a0bba58a64d75a1825": "aAn6t5", "5c18ff4b773bfb53807cb1b9c53efc70": "s2JAyO", "5c251158c8ac72cf9559e5a5ed17dd4e": "pM9FsQ", "5ce4e48821432e424c8f839546d1e6ec": "bcPoD7", "5ce7545f948086129592131003838377": "b7cLmT", "5dedf65c8171c537817bcf442d59f1a2": "S3tWCH", "5e3e07571bccf90e286f9a7689a29e49": "VD7gVM", "5eea3268b4f07e867415b774f4822106": "IwZzKE", "5ef2c3fcbfb6b9d4704750cc46260e35": "zYaxsj", "608da449b4e722638695065aa5697135": "VujsXn", "61214ee1af61095689b68f81906587e9": "Xq3hcc", "617ad0790a2b008c9e8e648591efe1e1": "aVOUjp", "61c7925481ae38ec114aba2a91cbc542": "VNLuDP", "6260ff37f33ead0055d212c442a80c37": "mdmjZw", "62773453eec664ab6d73cb7fe0cedbae": "E0U0RX", "63044e4ebfa225e128c07fe185df9265": "Mgwpq8", "641bbdeac9c29f16850f72a50aecb38b": "pmz7lF", "64231f6174642f8ca9bcbfb3a8e9f511": "pFbZAj", "643d3003d359f841c2e04c51aa9c68f2": "mID175", "64ea56b7381270469b07026e855a8dfd": "Pm0uj0", "6548b1b4bdd4808995e217687bf8f887": "vwHwC8", "656fe39a9618f2464ff084a01cfea135": "DfAmue", "66f9ca747f0490ede49c032f647860b1": "sZop3a", "6700df9b9a3b49212dd7f475a6d1da09": "m1O8wI", "673f49d5eb13e3745ddb80a4c2b33790": "MDyBsr", "6770e8a234f24420450d74803d976aca": "Gw3WaT", "686cb02f1c4659ce9851aebf0cec25a1": "ao9ZGb", "68aabd4c4646fcd08c52f84d5385dc30": "PXtGHg", "691353ea6d0edb7b4b8c8b2088d00979": "JBS7Rr", "69310d5a50bec4d0ef508379c6ac1eae": "RIzZKJ", "69762d156a1a171ca0eb3cbf7d491b54": "j24tdW", "69e689ab506bd7634056bd6b95dd3457": "pWNyqs", "6a5127a5ae3c35f1dd439e4cf70f8408": "1bpvbU", "6a6ac1e5f5e41876681d31aef01a0872": "t6Tiuu", "6b3435e77dc88b050cc49654b363a07f": "GyuWbb", "6bb411a859a63f0536e9383da8bee5f4": "Lkdltx", "6bfef91284a8dab6b1d574bb61039e2e": "HKRvok", "6cd342b22c596b43aa34ce975917b579": "45VBXm", "6d06b3fe18b9a2b7fc9e9944d3f32331": "Sfc3LZ", "6d3e197baaa01115917727e9859f8053": "uB6S6W", "6e2dec6d6f68a1838c4c024fabd2ce74": "qXSaSN", "6e5873ee5ba49c06f86e7fd9a48b6517": "kMpu08", "6e68c7ac6a7a3a5df4db8fbe58dc6c73": "OIJkjX", "6f014d4bc1a315b89852e591ac3b098f": "npQrzA", "6f08112659d765ab411c694956d99e1f": "BifNLh", "6fc4d58046ca70fffee1ad5edacf2b4d": "v6BxdP", "703c3cb07b6f069768b87841996866cc": "Svi8qJ", "7077a788b83ca98639d05823bccca41f": "aJifis", "70bd036c5c11e441b5bb2676da45ca60": "esdmyz", "70d4e49eb7d839d4554694c4fc80ba1c": "PT10rf", "70ecc87b6ece4f2666a7ce188c2f64ce": "wP8Go5", "71b206b986b39ac7b783572b80a2ef97": "CtZv4R", "71c3c8e473a92e099fbb418bd226fd51": "iw3kT2", "7200c09e8d0eb5f8369eb4f8fad3d758": "D7ruaQ", "7208f1715c64791cec3aa4a59f1ec3a6": "Nq45QP", "721e225012de6178d9c364aedbd807f2": "UJZtdO", "7249c6b2717a436011fc48d259ba2c77": "xx2hwz", "7359f47e8abf26270458560b368af413": "ffCjjn", "735b2aa97f3f16471e93e1d62cdf85f1": "O6AF93", "739e87d5c6156229e7b458ef4d20723b": "gyJGjM", "74a6962cf5f4d35987419d333597f054": "wJIcLx", "75250987feeb1d9313a213e200e8c7d7": "4JWpDq", "75324469283865a7ebd591f3ecccbeb1": "6izPba", "759b7030b60806b84ae040666100b41b": "hCrlWh", "75ffb917345269bcabd46c2a176fd595": "C39MT6", "769d536e5dcd4783876cd2dd626a22cf": "5ODfM8", "77fbedc306689793a268205fb2542940": "3CLHcT", "7818ebbe8fe5baea78437971cd5a28ae": "RfJQw8", "781f86275178422f6e18bd1615a3fc93": "0By01m", "79bd79779b3e50c4d8350f5d40b038db": "lP31K6", "79d83d5544e3d2e2d83e185fec24fd29": "eNapeD", "79eb6f04c9dce7c43760bb24708e8268": "JuOcBe", "7a5512bfd66144eaaef056c66861b533": "NxbAXH", "7b768e6a6b682a870dae4ac5603c3dc2": "oVYWZA", "7c34f6a5d5c5363fec465c30c9f22b7f": "QRBCNj", "7d4a9a34343ca7127b5a34430100b526": "Z6D4Vt", "7d9d64f6fec850a2f01f191ed7324c82": "AHhM2y", "7da68cad822b67fcdf299eb721fb3fa2": "A6UxDQ", "7de622a5d5d50cbee227ae268d756fa1": "RhW41M", "7e254440e0b3d4247bdf75bdd0cf4c81": "HXD0os", "7e5fbb086b12beeaa3b5b64fc93d981b": "EnarSD", "7f1e0e40b63a8781f3efa20b1de1df37": "oB7hxf", "808a4de3c8e36e41500829cb7b86fd8a": "ghkCHz", "80a0c7bd4a527d7bf3c344b244568eb8": "zzAKwF", "83462e0da479b7b47ba00f99b1ee9912": "SJE06K", "834982b47ac67c1724fc49f60e64b31e": "Ax7Raj", "84218509a634e0577bf1f34e7defc2ec": "OHpFfj", "856c1aaf6b5d505dda2e66fbe69cded1": "1A2f4p", "85f5c682d231cee8b629eb00409cd16d": "kpzPYX", "860641c83670979d25fefe6412cf3825": "VmzKX7", "86347a19ce77d0249ee0939d128125c8": "xKpDf6", "863dab89f3b7a9f663e4ebb07c20484d": "vdblrr", "86c88d228bf447bb220baec820857382": "rnVyjX", "86cf900ad3d4febd0f32634c2bfb29bb": "R1EJ5u", "8734fbdd722f5ff8bfe2014e6d1a955a": "nmcmPo", "88926431b04e13be7fd22160b5aa9b14": "quhHw1", "88f7e10343289c087b259a7a4beb7bca": "13NRWm", "8af1a119b6df3333e30ffd27f84ddb17": "jXQJ8j", "8b215a7cd85acf5290e9b2c6b957c2a0": "0tPo46", "8b8441465c558c1a8e06f1eb68a7ba32": "5NoiNV", "8c0b2dabd366ad7dff964f09ff82aec7": "ic0WuV", "8c3bef73e43bb7c17521e19e1c7a3102": "dkOinN", "8c7d5da431a1df5dc9827718ceed2bd1": "SnyqKH", "8c9c1da91a3617a8710b95c6d571f37e": "y5U4vH", "8d0a864e74b5389dec21af665b531190": "VYAaFL", "8dd8a6d0b5042602a854148f9d25dfac": "ftSQik", "8f54b179364927de631e8136fe481432": "FrybiS", "90de46afa3e5aaa7655f139466a03975": "wFpJ43", "90f36cdaee2bc80df306751b010c3157": "E3nHGN", "9177de3ecb6228e204c0f8c85f1df87d": "PP2GKh", "91db9a08d78ebece872cebc6066009c4": "3fq7dv", "91fd7fb85ecb1b262d7ff1f10a3700b5": "UymnpM", "91ffccec8abf2a59f16babcce220f0d1": "mCnmo6", "9220c7c562e35d691398380baf5ba44c": "qSrLyC", "924c550fd44d33ce5c43bdcd68aea77c": "xi8XKp", "9316f21b9d68230d0815ea104df5e54c": "zjFF9S", "9317f0999471dcae74ff8842f34fffa0": "NGEEi8", "943918c7ba0ec22d7ac7bc1f2ccdb82c": "5aZf3b", "94c224dff1b200053f5dad5d1e79caaf": "6rL6Lb", "955407807435725dc074370e91c49e80": "ODc9vh", "959ab0301f81944db128477205dc0da8": "ZEoRg5", "95fe1558911723c4d8ddbe6ec49514f6": "iAUJLL", "96a85667e621ea08471c8649fbc5cc22": "biOry1", "96d7784ad4e6b688c767d1393ecd6c3d": "pQLfi0", "9705a0a9410150e0a686427d08a07b88": "HPOjVT", "97410483be91cb6dc9c75b08d98d4537": "3LDPhM", "97ea08e52ecfba9f893ee223fa2cddf0": "0ydUcv", "97efd072f28df5cc33c10f898f91cade": "pICZ6J", "98354e3ea8fedffbe03aa18f51531839": "NgtwMl", "9850414c27e8b9a1bbb3cdd890407ed0": "ddTtFH", "9866ee350a9f7b2c8c97ca4cb03ecac6": "mDEvSP", "98d83cca8c71a6fb8ae0802a59704571": "MV4Ba6", "9911a7d69142f219f1cba23f1eed8443": "nLhkTT", "99320de70ddc193ffb6193a1a4b61e1f": "PVYli1", "998aa692c65cc11e57c6b0922499ccb6": "QcW8hz", "99b026e9a46a11207e65c7388164fa13": "Xb2Bfq", "99cd14ce4010720d8e4c6c028f4cc652": "CMLrbO", "99e3347a0accfcda4d32a7af4de93d02": "VIrXRs", "9a2293b65aa529034fc357d9dc3464aa": "P0rmSQ", "9ab7ef1903570456172bfaad0c1625f3": "pR52IA", "9cd6de6e16d5db206cad5a663118eaa0": "WClIda", "9d4238854b10144cc1ebf665b640561e": "onZ0ul", "9da0036d56b2b4aa83ef920e0ee872ae": "3oPF8J", "9e1d398a108eed08e933bdb6a5700965": "7jfGTA", "9e859c1e8f14475154e37603bbaefe66": "Mqhnen", "9fcc678b5d4a81371689b96edfffc1c9": "6NTKEP", "a013abc276ba980331f7053f2822f1b0": "P4ayzW", "a14722a30c847fc19b7429fcaf2d6724": "jzZJK2", "a160f160828f4d60f418032681642d9d": "6rAhcs", "a1ed5c043060a9f2d9cbb59deb7be1e6": "oRduOs", "a24b5de5fa475f9495f85acb20efd05e": "QjQVRX", "a28b51ed483648285241b810f549f0d7": "5Y2foQ", "a3fea72331188a4a2d9288599dc4eba8": "9zeg5F", "a4c629aa92dd8d53d94c7452eeb3f123": "zFS03K", "a5777476a8063c00cc8bfb50f7959929": "l98CMj", "a61802cc17affdba78ba02715faa6f7f": "849kR6", "a6cd247158937cd9e6994c12649d3379": "Rthlaw", "a6f5c2f338a8b76db0fc3d91cf269d46": "NwmWJ3", "a70f8648b7eb484b858c386085cdbac3": "vR9Um1", "a7c6d3e939e0f237eba89ede8c4ee0d8": "2naguo", "a7ddcecef5808354ef76994d3299d963": "PBe5c6", "a809092b4878cb3bbe397b69023637d2": "ZFuR9V", "a8cc09ef8a49690c7bba174e722b85ac": "RhbDJl", "a9f5b442351493390b672574a3d6201d": "aWwgPw", "aa3fb7b0e528d7dc93091a42ba5ca2f6": "At8mEq", "aa4d1b03fd9db9e0ae1a7fa853b578c8": "HaTtq0", "aa9c5316a8f082bab4ada96abdafe3a6": "lIip2D", "ab5701f88a3bae6a111af80d4c3ad066": "v6oZN1", "ab9832d818ea8a0ff9bbe96e0306c4ef": "MICrWV", "abd4552cf793e96ecddc745660c2a236": "0G3K90", "abd4f20e92a6e907da455fdcb05c80a5": "IDsn0Y", "ac5bad35ea85564ff4c74f99b0d709b9": "xIs1HG", "acf7f9a73cce20259be98166686674aa": "3YraRD", "ae08c8401165ed7d51e588f9d49f940c": "Qiedrd", "ae1e26d0ea08d737c4a7c37c411cf878": "bEA7hL", "ae1e87beb2f6b8c0b94ccd956480d0c0": "j44U70", "aec49e6ee1895c7af62d14a24a43f19a": "F7qTMS", "aed128ddb211adc9c2edce3bf7900f7f": "YEckkP", "aee3c87cc3efe49c85102b72e68834d5": "lSx6fs", "aef684ffd036bc862519ef22cf3bcd9b": "vacAuf", "af3f887397080401f1f6af910fec288c": "r5r6HX", "afadcc0371753413e5d5aaba4ad5310b": "v6gdat", "aff63347df21766d6f7f1cbbf99629e3": "omZaJx", "b000d76fb4df5191331b1d1678634f29": "7iIDio", "b0025f65f266721c71dfea4c6dc6cddf": "5QUDVS", "b12b7374e47efb54f69dbcb8e5af8146": "pReyOw", "b2bfd5f0ed9fd7774f3bfcae96c008ed": "gckUcn", "b2f25b2f5b84c3619430f642325a6a0f": "bDaM3w", "b320af637a950c4315e2afde4c11dbe3": "ozqyhd", "b32ddffb492d550bb427b4123d7a54d9": "OqXLln", "b350b0d564178d5c023835c6887a02f4": "XWDZB0", "b3eed07b49c6fb3393f0a9481bd4e52d": "moW94B", "b4914242810d82425d8558403f604de3": "7E4F0B", "b49450cfa3176e984eccc63c7f02aacd": "qp4W27", "b4ea64d7795c0cfcbd3f236df83657b2": "ISdidH", "b4edcae4da50ea5365245f86839315b9": "1bOKKL", "b50700bf52c8026f88272c36e3ba347b": "KWkbvY", "b6e1279bd63fb0842df5350d7a80cbbd": "li2SdZ", "b710f58063d3f5b99fc23ad34338cfa0": "wogO8R", "b71ab35ef5e1daf22c80622db5b67c4e": "QsJ43t", "b73672b191ffda7fbfa81096b2bf4746": "F9vakc", "b73823e867947ea8352c5ca206e20917": "IPnLkW", "b77b75d3a257cd781e2fea12bcce5919": "ZrwNaN", "b7a302b19db4149cc3b9b68be53f53ec": "JsgdTR", "b86f92ae4a3d3ff59e7a337af5f22938": "An2qRA", "b9fbc55da2c73d87e6cb978bd1c2aac5": "Tvp1FX", "ba019f8f9a9b112390d149e5c75d7533": "wtvkUu", "ba89a8f6b77aac12fffd163b2dc8f64c": "Sx8gHw", "bab734d0bdca57429d4688ded450da1b": "HpoEWc", "bb07e2c632886217f9c02c358b823c23": "9O0Kzw", "bb0b0b357378f765b9291a40dc3fcc62": "XSe4cm", "bb0b77965119f0e3edec8571e3a2f601": "4Ogpys", "bb90e29eabe582e073ab720a66708382": "fav5U3", "bbb2558539f55f715ad58d62ef357242": "1GIVX5", "bbff1a70807d449feab29842b2c9a307": "EGhIL0", "bcd375be628937e7bffb5ce24e05455c": "RAYmrn", "bd116dc06b240e22a6d680a89ba2c728": "SicWLU", "bd3f03dd3bc131abed4c0c61aadd3671": "zNSgiM", "bd5fbaa7512a26b674a7d8919148d0a4": "UNwSJU", "bd9128b366256cdb46ac37db7787564d": "1RMfya", "bdcebd95572cb2bf41ef252e3f8e545c": "ZtUHbX", "beaadbccafb9a81e95c7cfd2a3a94e9d": "zyLUbt", "bec7c90d007bf1ca939e6bb0e19c0349": "4WiyRu", "bf4a45ec6225a8465c630dffef1a1167": "PavoKU", "bfbdc9c3f38f7dd02152cd6cdd5be9fb": "V1DthS", "bfd0f7ca1682301d821eb8d4bf2c633a": "jBjmZp", "c0787cf00be5cf7403323c12ddd94178": "F3k3qo", "c1bedafbb76523d5af6361d895d8a76c": "WV3kI7", "c20e5e87c94f00e2000915b958b09774": "BcIXhk", "c2220f408598d29cd32b0b58992bec5d": "s9I7ij", "c23a99ad3f2dcfa1051e3d1efe8b90cd": "JikvMD", "c29fdfee8926ebf13ccb66ebe090972d": "GTMip5", "c2c04960af41f4b2d933b5424a1046f7": "Ra0D80", "c2eb8de00039ee52bead534700662932": "vP6i4C", "c31d313093875b14bc88244f6b322701": "qaaExa", "c3b1a778c2bf711e837d6837fa741acf": "Spf1Lk", "c4091aaa78c5faf5960c4fe519c0dc62": "mHrjvI", "c4d7e1aede5b8eafa0cbd2a81c1a8c9a": "gfJSNL", "c505af22132426a70a97b7cb51dca070": "7Af88Y", "c533a4a156657945567bba9dfdd95377": "FIeVi4", "c552138dd116333107f284d11e5d18fd": "3j3pmf", "c6147c14ff0688cfaca99ea087c0c257": "vnu4Jt", "c62179eed44a3734bce5a34470196950": "VoSNBB", "c648f2f33edcf717cb182f794295c481": "QGrIIK", "c724b8030fbd9c6f22bba744434f044b": "asZ4hQ", "c7372690825b18ab52237a1a97f4b06f": "X2l4EP", "c75005a75934c6f40b78b8e349adad1a": "iU0V1h", "c75d767c339c7500e858411a5c6b9751": "WiHCdL", "c7b61d6ef1b9e8057aa6f3b93d5b448a": "KE8zr8", "c80503477534e486bbb97203e21a581f": "TSKMVg", "c8411bbe6ed456c89c6ec6ca84e46cee": "QZvuiM", "c872e9884eaa5e229b09d70ac8484f7f": "Jo189x", "c8a34ac2f783448424167c25e626c3ac": "QEXGNu", "c8ea821a598d10b82b1e5561772dbf0e": "9WuNI9", "c9a2257a6aaa3d33afc7891ce3ed01ee": "j9VkcK", "c9ac84ec253a7784e9f033e38f8df831": "pn12NG", "c9eae2a50fd8a37fd06974fdbb8411b3": "lNzWZH", "caf6c90ab215f3b898a2a974dde5145a": "TwGMJs", "ccacafabe512a7e89599f9d02fc6a086": "9HMJ2H", "ce6b6ce9f688e1392e734186d3a57fcb": "kaCSTw", "ce8afb23566219579471b1d65399941a": "bpCM8l", "cee3f1b157fd4c63c348110743cd6359": "mXXWyD", "cf14c1d4e5699e22367bee914e353808": "Af0ys4", "cf21191feb75f625570adb3d386ba7fa": "NcIMiC", "cfd42f24f7738a9d1300bdd8fa99befd": "rhvSMP", "d012627f48103f7c87a3cc6af450eea3": "XOXiTZ", "d0cfda60ce66bdfb906dc31c1ef428f9": "t3XpUE", "d0e4f1cd3ec3c885ac81e1afd7c35564": "Ro89BO", "d181d62306f91212feea923efbc5b7f1": "Mfiz1z", "d1c7082469a9e2d30b54665af651cb47": "l9Wuvr", "d225c8089ac9102cec9456a3c9bbb62c": "qlSHOT", "d23d857ba120a9166b613316011befe6": "Sd7hwk", "d287f2f8821ea3a3927239242afde683": "hkfERs", "d2e89e78d7c3f3d33e02cf7a0cd212aa": "Xz9Pg5", "d317cef54bfb88f2b8d079b4fdaffce3": "aOpMR1", "d33e123b295d155d0057c7a13491c7a5": "pvHCBE", "d41d8cd98f00b204e9800998ecf8427e": "rFJzKF", "d4e358a261ee3855c011a13ebe7106c2": "GyJ46g", "d52d120f3ffe53c3bb4ac96e01140256": "sdjFzx", "d858237b832c02cad1022800c87e85b2": "mB5qCS", "d946ec17b8da953842f32ae535a7a1e4": "Tgip6m", "d9a3e989d896f4feae861b23a4d70018": "kHjSQj", "da7ab34b49227b8f2857aa5ddbf4b257": "IMK8hy", "db00f4304e254c0d4a8bda7116510ae8": "IHyFYa", "dbc8c60ed470d26f5a301486b9007be5": "zOUZsC", "dc66efdf28959720e2d1c097502b9b78": "oEuEsM", "dd6e5a395e95253da2aa58a1de98e496": "XsmZvD", "dd84b1ad65ba637eb979c709c83bd47a": "K8UErc", "dd9d72fcc094cedcbc6cb910646a3a9e": "JUC2Gg", "de58cf4b45c0c72922c42db31f4a69e5": "EO5umY", "df86e779dc56d0706ff78d92891fac01": "913fpA", "df9eb6228cc882ae027d984485a789a4": "HI4Z9J", "dfa2df193655f59682ba947de096b587": "d3M0BM", "dfc9ed04596c723f67d639c0a2dfa9a0": "K2ZJvD", "e066ce5de88136cbd87c5961654e22f4": "4zLC9g", "e130b00baf1733737edc66cbda90ae10": "9kQAAP", "e1be5422e43aacfcddc72e1493ce231b": "ZNnr5K", "e22cf676ff4852c13e5c1da089c8e616": "D1VFQD", "e259e4af1fed4135a678c9accdaafbbb": "z1mhZh", "e3354055aeaeb3c87347dd95eaf431c6": "E5mi7e", "e44d3d1ae1458bd96e75e653bc0bee68": "MT1xQi", "e4afed600a4134e33f9d55efaa3a3b13": "NKGPw0", "e5515d7484afaebd9be77f605de98bca": "d39TO0", "e56dc95035095b22c4871ddd19214b15": "0ujCjh", "e58201ae4489927e53c7771e2e1ab6cd": "TV5RJ1", "e63121fdec2e23fb55f87d9f6c89a20a": "C7d4dN", "e633900df216bed714b28527ebecc595": "H8OEw0", "e67524bc869005dac90d30dbdf6f4b6b": "kusFJU", "e6dbb8678ba86541844f38fbdf9f9962": "7BiJ63", "e70fa2ac9e3f6a70e042b5662d04b320": "F7iPTE", "e7648a93766e08e8cbce9ac71cc00a1f": "fAe9VU", "e833bad8b1e51201ec9ff33281b7c7a0": "nAtnTK", "e83c6f83369141714fe247f9837e3407": "62kHJw", "e852ad3f3be3d7679d48f5ac6eafcc4d": "8LslL7", "e8920568595ec74b4ecba442a40fe975": "i1ACKH", "e8da86a08fe4097b0f0bc248e18a8267": "F7GiKB", "e8f4783aa58191acb361bd425ee0821b": "1fEPVQ", "e9d00ba1a41cb827e70515ca81dc3b6d": "D19YmM", "eb38b404c151d19c981e6263499fb51a": "obX6EA", "eb66a7fa866945879543f5150aba72fc": "YBRu0R", "eb85ec762d767029249b4cdf7a739f50": "KcJb9N", "eb8be1c977c8b8ace5d562723eb9c7d5": "mjfE6T", "ebb37d172e27c0fdc7ca708eb1c53a25": "13ALUD", "ebea5f98611f42b3ebc9ec25cb060c3b": "QvhIK5", "ec117287383785d8ec7c14e9d18b4abb": "HdQ0xY", "ec224acb5c74da3a541cdfbde6501895": "fBAmRl", "ec489d71080beb740e0508db2e5f6f1f": "tmUvPV", "ec6f46380bec2ca00c6219bdf2c06dd1": "9RmuVK", "ec8a1ba5aad036a07f05e1be9b0246f0": "xlYSR9", "ec90240d90c211768aca215dc9ea64fe": "7vEZY5", "ed3a882092122e78bf71e6cb7a3e2769": "aTvAPh", "ee50f36458172ab4fbd0b2bbf802a5a7": "gwEYTP", "eeca677b9be1c866e23508337e53925e": "teKmvq", "ef2cb14c35a37f0f4b8e07e0968e150d": "6j78IA", "ef5e67965d9edb653d01928ca0013926": "d9htjc", "efdff8b6822ab048ec8f153a617d4df6": "2h4Acd", "f10fc10b802dea9677a2e1bcd622727e": "3QF9UO", "f1d7a9b115fff218bb11cc155fe901ba": "lxvR1W", "f1dc59dff6f0f78bffca77a0abdb06b7": "CRx1TX", "f202e1c7bbd7e4decf61493fad965bfd": "wt5slm", "f210df3826e74727b055c83f9d3d13bd": "2f5bQc", "f24c5fef8c90f4a490c13c9e9b31942d": "uDu9Ul", "f294eba4eb12caaea6cc83c54636ad19": "leztls", "f349d200b7b3555895fc6addacec0979": "GSrfs8", "f353b8633d3211c9e1bfdda02f51feb5": "zUIcm9", "f40911f472378789b16c91e96052e81e": "EOf4xo", "f43f50936fc4aa99cb627cdc9b6330bf": "6B47as", "f46abe5cdc92c7a47f9dc6ba181ae951": "TKeIIJ", "f493e20702f74b0d29109aee43ff76e1": "wKvwVO", "f4beb46d55e210988d686d22b31e5b04": "PEkvmW", "f4e5d9da4a78aa5a58acc03f19d00dfe": "lqvqF5", "f5f59f055a9912a1e9ce99d333d6110f": "OJbvYL", "f6080e5e9a8bae92734b2cbf1664d6b2": "uWWzrY", "f60fc6641e1f39a777db41a99a832ac4": "0LQg7Q", "f695c3dac97a303d5bff8105c2051b42": "xDODG2", "f7011e97ff3d1236204bff916a141d04": "lGukPN", "f71b4dde2ab3b4275d2e3dc9a29a4653": "ZAbM6C", "f75013ce7eaae6139df1dd53a0a806ed": "FfLkj6", "f755fca9aa0b596f98a902e57e5767b0": "DVQD7U", "f817f334bbc43eee589f09a9dffb9672": "Ji6DYE", "f86e7c90924c89e1ef8a737b790d8772": "So5ImR", "f8aebf6fbc9ed779e91322883a6c9ce8": "KPXGZv", "f95717bfd81aa8dbc1513245bd67b6be": "JsJhRc", "f988886470331dccc8ec086c41bfafcd": "qoy8RA", "fb0d24855ffc4243b6a41e589b18c4e6": "Z126q1", "fb1ff2e786a4652ecfc68ef8c2c0ccf6": "yUyUuR", "fb6c8751fc9b79c47afc93aebf47aff4": "qLMImy", "fbc62d204161e3c27b475cd977d46688": "Vl9zVp", "fc617ccb710cd555d877583d15733901": "jLrzeh", "fd246e1a3a16f8a50d7e273e0827d375": "eWsDPZ", "fd3fe8e362644375bfb459d621bcf60e": "m8nPse", "fd9e3814c8d16a302143959ebcd226c8": "fdiaxj", "fdb6d5e83df4c2f4c14210268df3f908": "qrkDAq", "fdf631eb0ab4787c4db7332bdf1ce7ca": "cB1u9Q", "fe53b89d88460c2372e88b9d4930f3f9": "Hp0Fhu", "fe80894d19ad6b77f0cf218b220af953": "7ivBcg", "fe8437a27fbaf6d3514cc22ebeadfde2": "fUgN3u", "fecd58c28b1044cb1e0d2da8daeec0e9": "hdqDUd", "ff1c83271cc1fafb48d86af42236cfb1": "VQNEMo", "ff853f821b142f6b2ff3304ac875c220": "PRDuAM"} \ No newline at end of file diff --git a/languages/cprogs/.idea/.gitignore b/languages/cprogs/.idea/.gitignore new file mode 100644 index 00000000..8bf4d45d --- /dev/null +++ b/languages/cprogs/.idea/.gitignore @@ -0,0 +1,6 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/languages/cprogs/.idea/cprogs.iml b/languages/cprogs/.idea/cprogs.iml new file mode 100644 index 00000000..f08604bb --- /dev/null +++ b/languages/cprogs/.idea/cprogs.iml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/languages/cprogs/.idea/misc.xml b/languages/cprogs/.idea/misc.xml new file mode 100644 index 00000000..79b3c948 --- /dev/null +++ b/languages/cprogs/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/languages/cprogs/.idea/modules.xml b/languages/cprogs/.idea/modules.xml new file mode 100644 index 00000000..02c2a389 --- /dev/null +++ b/languages/cprogs/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/languages/cprogs/.idea/vcs.xml b/languages/cprogs/.idea/vcs.xml new file mode 100644 index 00000000..b2bdec2d --- /dev/null +++ b/languages/cprogs/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file 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.12_word_per_line.c b/languages/cprogs/Ex_1.12_word_per_line.c index 2955fc22..6d1e081f 100644 --- a/languages/cprogs/Ex_1.12_word_per_line.c +++ b/languages/cprogs/Ex_1.12_word_per_line.c @@ -4,24 +4,28 @@ * * */ +// concept is: do nothing if you meet more than 1 blankspaces or tab spaces or newlines or "anti word characters" + #include -#define IN 1 -#define OUT 0 -/* This program counts the number of lines, characters and words */ -int main (int argc, char *argv[]) { - int c,state; - state = IN; - while((c=getchar()) != EOF) { - if(c==' ' || c == '\t') - state=OUT; - else if (state == OUT) { - state=IN; +#define CTRL(x) (x & 0x1f) + +int main() +{ + int c; + + while((c = getchar()) != EOF && c != CTRL('d') ) + { + if(c == ' ' || c == '\t' || c == '\n' || c == '-') + { putchar('\n'); - putchar(c); + while((c = getchar()) == ' ' || c == '\t' || c == '\n' || c == '-' ) + { + ; //do nothing // we could actually skip the braces and just enter ; after closing the while's condition brackets + } } - else - putchar(c); + putchar(c); } -} \ No newline at end of file +} + diff --git a/languages/cprogs/Ex_1.16_LongLine.c b/languages/cprogs/Ex_1.16_LongLine.c index a147f2f6..01e19ed0 100644 --- a/languages/cprogs/Ex_1.16_LongLine.c +++ b/languages/cprogs/Ex_1.16_LongLine.c @@ -1,63 +1,100 @@ /** * Exercise 1.16 * - * Write a Program to print the longest line input - * + * Write a program to print the length of an arbitrarily long input line + * and as much text as possible + * **/ -#include -#define MAXLINE 1000 +#include + +/* The size of the output that we would like */ +#define MAX 1000 + +/* define our functions*/ +int getNewLine(char line[], int max); +void copy(char to[], char from[]); + +int main(){ -int mgetline(char line[],int lim); + int len, max; + char line[MAX]; + char longest[MAX]; -void copy(char to[],char from[]); + max = 0; + while((len = getNewLine(line, MAX)) > 0){ + if(len > max){ -int main(void) -{ - int len,max; - char line[MAXLINE], maxline[MAXLINE]; + max = len; + copy(longest, line); - max =0; + } + + } + + if (max > 0){ - while((len = mgetline(line, MAXLINE)) > 0) - { - if(len > max) - { - max = len; - copy(maxline,line); - } - } + printf("length = %i, string=%s", max, longest); + + } + + return 0; - if(max>0) - printf("%s",maxline); } - -int mgetline(char s[],int lim) -{ - int i,c; +/* get a line in a character array */ +int getNewLine(char arr[], int lim){ + + int c, i; + + for(i=0; i < lim -1 && (c=getchar()) != EOF && c != '\n'; ++i){ + + arr[i] = c; + + } + if(c == '\n'){ - for(i=0;i +#include -int main() { +const char *input = "This\tis\ta\ttest\\string\bwith\ttabs\\and\\backspaces.\n\nnewline"; +int input_index = 0; - int char_count, num_lines, num_tabs, num_spaces; +int _getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } +} +int main() +{ + int c, blanks, tabs, newlines; - num_lines = 0; - num_tabs = 0; - num_spaces = 0; + blanks = tabs = newlines = 0; - while ((char_count = getchar()) != EOF) { - if (char_count == '\n') - ++num_lines; - if (char_count == '\t') - ++num_tabs; - if (char_count == ' ') - ++num_spaces; + while ((c = _getchar()) != EOF) { + if (c == ' ') + ++blanks; + if (c == '\t') + ++tabs; + if (c == '\n') + ++newlines; } - printf("Blanks: %d\nTabs: %d\nNewlines: %d\n", num_spaces, num_tabs, num_lines); - + printf("Blanks: %d\n", blanks); + printf("Tabs: %d\n", tabs); + printf("Newlines: %d\n", newlines); } 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_2.1_cal_limits.c b/languages/cprogs/Ex_2.1_cal_limits.c index 876be392..309e265f 100644 --- a/languages/cprogs/Ex_2.1_cal_limits.c +++ b/languages/cprogs/Ex_2.1_cal_limits.c @@ -14,15 +14,15 @@ * () casting it the required type again */ -#include -#include -#include +#include +#include +#include -int main(void) +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)); @@ -41,28 +41,27 @@ int main(void) 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); - + 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/languages/cprogs/Ex_2.5_any.c b/languages/cprogs/Ex_2.5_any.c index 67084e7f..07059088 100644 --- a/languages/cprogs/Ex_2.5_any.c +++ b/languages/cprogs/Ex_2.5_any.c @@ -45,28 +45,21 @@ int mgetline(char s[],int lim) s[i]='\0'; } + int any(char s1[],char s2[]) { - int i,j,check_next_char; - - check_next_char=1; + int i,j; - for(i=0;s1[i]!='\0'&& (check_next_char);) + for(i=0;s1[i]!='\0';++i) { // iterate through s2 while trying to find matching character from s1 - for(j=0;s2[j]!='\0'&& (s1[i]!=s2[j]);++j) + for(j=0;(s1[i]!=s2[j]) && s2[j]!='\0';++j) ; // continue - if(s2[j]=='\0') { - check_next_char=1; - i++; // go for the next char in s1 + 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; } - else - check_next_char=0; // match found } - if(s1[i]=='\0') - return -1; - else - return i; -} + return -1; +} \ No newline at end of file diff --git a/languages/cprogs/Ex_4.13_reverse_string.c b/languages/cprogs/Ex_4.13_reverse_string.c index 37cb5ebb..ce7c8c31 100644 --- a/languages/cprogs/Ex_4.13_reverse_string.c +++ b/languages/cprogs/Ex_4.13_reverse_string.c @@ -34,28 +34,36 @@ int mgetline(char s[],int lim) s[i]='\0'; } -void reverse(char s[]) -{ - void reverser(char s[],int i,int len); - - reverser(s,0,strlen(s)); +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 -#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_4.5_calculator_math_functions.c b/languages/cprogs/Ex_4.5_calculator_math_functions.c index ac5acb41..36a5549e 100644 --- a/languages/cprogs/Ex_4.5_calculator_math_functions.c +++ b/languages/cprogs/Ex_4.5_calculator_math_functions.c @@ -151,7 +151,11 @@ int getop(char s[]) 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!='-') 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_5.8_day_date.c b/languages/cprogs/Ex_5.8_day_date.c index e552647c..a5fa6336 100644 --- a/languages/cprogs/Ex_5.8_day_date.c +++ b/languages/cprogs/Ex_5.8_day_date.c @@ -1,3 +1,6 @@ +/* + * Error check in day_of_year and month_day + */ #include static char daytab[2][13]={ @@ -6,15 +9,24 @@ static char daytab[2][13]={ }; int day_of_year(int year,int month,int day); -void month_day(int year,int yearday); +void month_day(int year,int yearday, int *month, int *day); int main(void) { - int day,mo,dat; + 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); - day=day_of_year(1988,2,29); - printf("%d\n",day); - month_day(1988,60); return 0; } @@ -25,6 +37,9 @@ 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 (leap? 366 : 365)) + { + *month = -1; + *day = -1; + return; + } + for(i=1;yearday > daytab[leap][i];i++) yearday -= daytab[leap][i]; - printf("Month: %d, Day: %d\n", i, yearday); - + *month = i; + *day = yearday; } - 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 dcfe33bb..2e383d11 100644 --- a/languages/cprogs/Ex_6.4.c +++ b/languages/cprogs/Ex_6.4.c @@ -15,12 +15,8 @@ #include #include -#define MAXWORD 1000 /* longest word that can be read by mgetword */ +#define MAXWORD 1000 -/* - * tnode: Tree node from K&R2 page 140. Words are initially read into - * the tree by getword. - */ struct tnode { char *word; @@ -29,12 +25,12 @@ struct tnode struct tnode *right; }; -struct numwordnode +struct bynumbernode { int number; - struct words *wordslist; - struct numwordnode *left; - struct numwordnode *right; + struct words *wordlist; + struct bynumbernode *left; + struct bynumbernode *right; }; struct words @@ -43,229 +39,158 @@ struct words struct words *nextword; }; -struct tnode *addtree(struct tnode *, char *); -struct numwordnode *addnumtree(struct numwordnode *, int, char*); +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 numwordnode *traverse(const struct tnode *, struct numwordnode *); -void treeprint(const struct numwordnode *); +struct bynumbernode *traverse(const struct tnode *, struct bynumbernode *); +void treeprint(const struct bynumbernode *); int mgetword(char *, int); -int main(int argc, char *argv[]) -{ - struct tnode *root; - struct numwordnode *numwordroot; +struct tnode *talloc(void){ + return (struct tnode *)malloc(sizeof(struct tnode)); +}; - char word[MAXWORD]; +struct bynumbernode *bynumbernodealloc(void){ + return (struct bynumbernode *)malloc(sizeof(struct bynumbernode)); +}; - /* get all the words */ - root = NULL; - numwordroot = NULL; +struct words *wordsalloc(void){ + return (struct words *)malloc(sizeof(struct words)); +}; - while(mgetword(word, MAXWORD) != 'x') - if(isalpha(word[0])) - root = addtree(root, word); - numwordroot = traverse(root, numwordroot); - printf("Words and their frequencies:\n"); +#define BUFSIZE 100 - treeprint(numwordroot); +char buf[BUFSIZE]; +int bufp=0; - return 0; +int getch(void){ + return (bufp > 0) ? buf[--bufp] : getchar(); } - -struct tnode *talloc(void); -struct numwordnode *numwordalloc(void); -struct words *wordsalloc(void); -char *mstrdup(char *); - -/* mgetword from Ex6.1 */ - -#define IN 1 -#define OUT 0 - - - -int mgetword(char *word, int lim) -{ - int c, d, getch(void), comment, string, directive; - void ungetch(int); - char *w = word; - - comment = string = directive = OUT; - - while (isspace(c = getch())) - ; - - /* Check if inside a comment */ - - if (c == '/') { - if ((d = getch()) == '*') { - comment = IN; - } else { - comment = OUT; - ungetch(d); - } - } - - /* Check if inside a quote */ - - if ( c == '\"') { - string = IN; +void ungetch(int c){ + if(bufp >= BUFSIZE){ + printf("ungetch: too many characters\n"); } + else buf[bufp++] = c; + return; +} - /* Check if inside a directive */ - - if (c == '#') { - directive = IN; +char *mstrdup(char *s){ + char *p; + p = (char *)malloc(strlen(s) + 1); + if(p != NULL){ + strcpy(p, s); } + return p; +} - if ( c == '\\') { - c = getch(); /* ignore the \\ character */ - } - if (comment == OUT && string == OUT && directive == OUT) { - if (c != EOF) - *w++ = c; +int getword(char *word, int lim){ + int c, getch(void); + void ungetch(int); + char *w = word; - if (!isalnum(c) && c !='_' ) { - *w = '\0'; - return c; - } + while(isspace(c = getch()) || c == '_' || c == '/' || c == '#' || c == '*' || c == '"'); - 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; + if(!isalpha(c)){ *w = '\0'; + return c; } - else if (directive == IN) { - *w++ = c; - while ((*w++ = getch()) != '\n') { - if ( c == '\\') { /* Take care of continuation line escape */ - *w++ = getch(); - } + for( ; --lim > 0; w++){ + if(!isalnum(*w = getch())){ + ungetch(*w); + break; } - directive = OUT; - *w = '\0'; } - - return c; - + *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. - */ +/* addtree : add a node with w at or below p */ struct tnode *addtree(struct tnode *p, char *w) { int cond; - if(p == NULL) { /* new word */ - p = talloc(); + if (p == NULL){ /* new word */ + p = talloc(); // make new node p->word = mstrdup(w); p->count = 1; p->left = p->right = NULL; } - else if((cond = strcmp(w, p->word)) == 0) + else if ((cond = strcmp(w, p->word)) == 0){ p->count++; - else if(cond < 0) + } + else if(cond < 0){ p->left = addtree(p->left, w); - else + } + else{ p->right = addtree(p->right, w); + } return p; } +// treeprint: in-order print of tree p +void treeprint(const struct bynumbernode *p){ + if(p != NULL){ + treeprint(p->left); + printwords(p->wordlist, p->number); + treeprint(p->right); + } +} -struct numwordnode *addnumtree(struct numwordnode *p, int count, char* w) +void printwords(const struct words* w, const int count) { - if (p == NULL) { - p = numwordalloc(); - p->number = count; - p->wordslist = NULL; - p->wordslist = addwordtolist(p->wordslist, w); + if (w != NULL){ + printf("%d->%s", count, w->word); + w = w->nextword; } - else if (count < p->number) - p->left = addnumtree(p->left, count, w); - else - p->right = addnumtree(p->right, count, w); - return p; + while (w != NULL) { + printf(", %s", w->word); + w = w->nextword; + } + printf("\n"); } -struct words *addwordtolist(struct words* list, char *w) -{ - if (list == NULL) { + +struct words *addwordtolist(struct words* list, char *w){ + if(list == NULL){ list = wordsalloc(); list->word = mstrdup(w); list->nextword = NULL; - } else { + } + else { list->nextword = addwordtolist(list->nextword, w); } return list; } -/* treeprint: From K&R2 page 142. Prints tree p in-order. */ -void treeprint(const struct numwordnode *p) -{ - if(p != NULL) { - treeprint(p->left); - printwords(p->wordslist, p->number); - treeprint(p->right); - } -} -void printwords(const struct words* w, const int count) -{ - if (w != NULL) { - printf("%s->%d\n", w->word, count); - w = w->nextword; +struct bynumbernode *addnumtree(struct bynumbernode *n, int i, char *w){ + if (n == NULL){ + n = bynumbernodealloc(); + n->number = i; + n->wordlist = NULL; + n->wordlist = addwordtolist(n->wordlist, w); + } + else if (n->number == i){ + addwordtolist(n->wordlist, w); + } + else if (n->number < i){ + n->left = addnumtree(n->left, i, w); + } + else{ + n->right = addnumtree(n->right, i, w); } + return n; } -struct numwordnode *traverse(const struct tnode *p, struct numwordnode *q) -{ - - if (p != NULL) { +struct bynumbernode *traverse(const struct tnode *p, struct bynumbernode *q){ + if(p != NULL){ q = traverse(p->left, q); q = addnumtree(q, p->count, p->word); q = traverse(p->right, q); @@ -273,48 +198,30 @@ struct numwordnode *traverse(const struct tnode *p, struct numwordnode *q) return q; } -/* talloc: From K&R2 page 142. Makes a tnode. */ -struct tnode *talloc(void) -{ - return (struct tnode *) malloc(sizeof(struct tnode)); -} - -struct numwordnode *numwordalloc(void) -{ - return (struct numwordnode *) malloc(sizeof(struct numwordnode)); -} +int main(){ + struct tnode *root; + char word[MAXWORD]; + + struct bynumbernode *nroot; -struct words *wordsalloc(void) { - return (struct words *) malloc(sizeof(struct words)); -} + root = NULL; + nroot = NULL; + while(getword(word, MAXWORD) != EOF){ + if(isalpha(word[0])){ + root = addtree(root, word); + } + } + + nroot = traverse(root, nroot); -/* 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; + printf("Words by frequency:\n"); + + treeprint(nroot); + return 0; } -/* - * 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(); -} -void ungetch(int c) { /* push character back on input */ - if(bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; - return; -} + 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/Ex_7.3_minprintf.c b/languages/cprogs/Ex_7.3_minprintf.c index d1b3b32e..f6bbeb19 100644 --- a/languages/cprogs/Ex_7.3_minprintf.c +++ b/languages/cprogs/Ex_7.3_minprintf.c @@ -6,7 +6,12 @@ int main(void) { char *a="Hello,World"; minprintf("%s",a); - + int i = 10; + minprintf("%d\n", i); + int b = 011; + minprintf("b in octal: %o, and in decimal: %d\n", b, b); + int h = 10; + minprintf("h in hex: %x, and in decimal: %d\n", h, h); return 0; } @@ -39,8 +44,16 @@ void minprintf(char *fmt,...) break; case 's': for(sval = va_arg(ap,char *);*sval;sval++) - putchar(*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; diff --git a/languages/cprogs/Ex_7.4.c b/languages/cprogs/Ex_7.4.c index ca392bf6..3d1224b7 100644 --- a/languages/cprogs/Ex_7.4.c +++ b/languages/cprogs/Ex_7.4.c @@ -1,53 +1,74 @@ -/* - * - * Write a private version of scanf analogous to minprintf from the - * previous section. - * - */ - +/* minscanf: minimalistic scanf function */ #include -void minprintf(char *fmt,...); +#include +void minscanf(char *fmt,...); int main(void) { - char *a="Hello,World"; - minprintf("%s",a); - + + int i; + minscanf("%d", &i); + printf("minscanf input: %d\n", i); + + char * a; + minscanf("%s", a); + printf("minscanf input: %s\n", a); + + float f; + minscanf("%f", &f); + printf("minscanf input: %f\n", f); + + int o; + minscanf("%o", &o); + printf("minscanf input in octal %o, in decimal %d\n", o, o); + + int x; + minscanf("%x", &x); + printf("minscanf input in hex %x, in decimal %d\n", x, x); return 0; } -/* TODO: Convert to scanf */ - -void minprintf(char *fmt,...) +void minscanf(char *fmt,...) { va_list ap; /* points to each unnamed arg in turn */ char *p,*sval; - int ival; - double dval; + int *ival; + float *dval; va_start(ap,fmt); /* make ap point to 1st unnamed arg */ - + for(p=fmt;*p;p++) { if(*p != '%') { - putchar(*p); continue; } switch(*++p) { case 'd': - ival = va_arg(ap,int); - printf("%d",ival); + ival = va_arg(ap,int*); + char * d = "44"; + sscanf(d,"%d",ival); break; case 'f': - dval = va_arg(ap,double); - printf("%f",dval); + dval = va_arg(ap,float*); + char * f = "5.33"; + sscanf(f,"%f",dval); break; case 's': - for(sval = va_arg(ap,char *);*sval;sval++) - putchar(*sval); + 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); diff --git a/languages/cprogs/Ex_7.4v2.c b/languages/cprogs/Ex_7.4v2.c new file mode 100644 index 00000000..d3b5bac4 --- /dev/null +++ b/languages/cprogs/Ex_7.4v2.c @@ -0,0 +1,43 @@ +#include +#include +#include +//compare two files, printing the first line where they differ +int main(int argc, char *argv[]){ + FILE *fp1, *fp2; + void filecmp(FILE *, FILE *); + char *prog = argv[0]; + if(argc == 3){ + if((fp1 = fopen(argv[1], "r")) ==NULL || (fp2 = fopen(argv[2], "r")) ==NULL){ + fprintf(stderr, "%s: can't open %s\n", prog, argv[1]); + exit(1); + } + else{ + filecmp(fp1, fp2); + fclose(fp1); + fclose(fp2); + } + } + else{ + printf("%s", "Please enter two file names"); + } + exit(0); +} + +void filecmp(FILE *f1, FILE *f2){ + size_t size = 100; + char *string; + char *string1; + + while(!feof(f1) && !feof(f2)){ + string = (char *) malloc(size); + getline(&string, &size, f1); + string1 = (char *) malloc(size); + getline(&string1, &size, f2); + if(strcmp(string, string1)!= 0) + { + printf("%s", string); + printf("%s", string1); + return; + } + } +} 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 978afcdf..00000000 --- a/languages/cprogs/atoiv2.c +++ /dev/null @@ -1,34 +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/mined1.c b/languages/cprogs/mined1.c deleted file mode 100644 index 7c1f88fb..00000000 --- a/languages/cprogs/mined1.c +++ /dev/null @@ -1,1987 +0,0 @@ -/* - * Part one of the mined editor. - */ - -/* - * Author: Michiel Huisjes. - * - * 1. General remarks. - * - * Mined is a screen editor designed for the MINIX operating system. - * It is meant to be used on files not larger than 50K and to be fast. - * When mined starts up, it reads the file into its memory to minimize - * disk access. The only time that disk access is needed is when certain - * save, write or copy commands are given. - * - * Mined has the style of Emacs or Jove, that means that there are no modes. - * Each character has its own entry in an 256 pointer to function array, - * which is called when that character is typed. Only ASCII characters are - * connected with a function that inserts that character at the current - * location in the file. Two execptions are and which are - * inserted as well. Note that the mapping between commands and functions - * called is implicit in the table. Changing the mapping just implies - * changing the pointers in this table. - * - * The display consists of SCREENMAX + 1 lines and XMAX + 1 characters. When - * a line is larger (or gets larger during editing) than XBREAK characters, - * the line is either shifted SHIFT_SIZE characters to the left (which means - * that the first SHIFT_SIZE characters are not printed) or the end of the - * line is marked with the SHIFT_MARK character and the rest of the line is - * not printed. A line can never exceed MAX_CHARS characters. Mined will - * always try to keep the cursor on the same line and same (relative) - * x-coordinate if nothing changed. So if you scroll one line up, the cursor - * stays on the same line, or when you move one line down, the cursor will - * move to the same place on the line as it was on the previous. - * Every character on the line is available for editing including the - * linefeed at the the of the line. When the linefeed is deleted, the current - * line and the next line are joined. The last character of the file (which - * is always a linefeed) can never be deleted. - * The bottomline (as indicated by YMAX + 1) is used as a status line during - * editing. This line is usually blank or contains information mined needs - * during editing. This information (or rather questions) is displayed in - * reverse video. - * - * The terminal modes are changed completely. All signals like start/stop, - * interrupt etc. are unset. The only signal that remains is the quit signal. - * The quit signal (^\) is the general abort signal for mined. Typing a ^\ - * during searching or when mined is asking for filenames, etc. will abort - * the function and mined will return to the main loop. Sending a quit - * signal during the main loop will abort the session (after confirmation) - * and the file is not (!) saved. - * The session will also be aborted when an unrecoverable error occurs. E.g - * when there is no more memory available. If the file has been modified, - * mined will ask if the file has to be saved or not. - * If there is no more space left on the disk, mined will just give an error - * message and continue. - * - * The number of system calls are minized. This is done to keep the editor - * as fast as possible. I/O is done in SCREEN_SIZE reads/writes. Accumulated - * output is also flushed at the end of each character typed. - * - * 2. Regular expressions - * - * Mined has a build in regular expression matcher, which is used for - * searching and replace routines. A regular expression consists of a - * sequence of: - * - * 1. A normal character matching that character. - * 2. A . matching any character. - * 3. A ^ matching the begin of a line. - * 4. A $ (as last character of the pattern) mathing the end of a line. - * 5. A \ matching . - * 6. A number of characters enclosed in [] pairs matching any of these - * characters. A list of characters can be indicated by a '-'. So - * [a-z] matches any letter of the alphabet. If the first character - * after the '[' is a '^' then the set is negated (matching none of - * the characters). - * A ']', '^' or '-' can be escaped by putting a '\' in front of it. - * Of course this means that a \ must be represented by \\. - * 7. If one of the expressions as described in 1-6 is followed by a - * '*' than that expressions matches a sequence of 0 or more of - * that expression. - * - * Parsing of regular expression is done in two phases. In the first phase - * the expression is compiled into a more comprehensible form. In the second - * phase the actual matching is done. For more details see 3.6. - * - * - * 3. Implementation of mined. - * - * 3.1 Data structures. - * - * The main data structures are as follows. The whole file is kept in a - * double linked list of lines. The LINE structure looks like this: - * - * typedef struct Line { - * struct Line *next; - * struct Line *prev; - * char *text; - * unsigned char shift_count; - * } LINE; - * - * Each line entry contains a pointer to the next line, a pointer to the - * previous line and a pointer to the text of that line. A special field - * shift_count contains the number of shifts (in units of SHIFT_SIZE) - * that is performed on that line. The total size of the structure is 7 - * bytes so a file consisting of 1000 empty lines will waste a lot of - * memory. A LINE structure is allocated for each line in the file. After - * that the number of characters of the line is counted and sufficient - * space is allocated to store them (including a linefeed and a '\0'). - * The resulting address is assigned to the text field in the structure. - * - * A special structure is allocated and its address is assigned to the - * variable header as well as the variable tail. The text field of this - * structure is set to NIL_PTR. The tail->prev of this structure points - * to the last LINE of the file and the header->next to the first LINE. - * Other LINE *variables are top_line and bot_line which point to the - * first line resp. the last line on the screen. - * Two other variables are important as well. First the LINE *cur_line, - * which points to the LINE currently in use and the char *cur_text, - * which points to the character at which the cursor stands. - * Whenever an ASCII character is typed, a new line is build with this - * character inserted. Then the old data space (pointed to by - * cur_line->text) is freed, data space for the new line is allocated and - * assigned to cur_line->text. - * - * Two global variables called x and y represent the x and y coordinates - * from the cursor. The global variable nlines contains the number of - * lines in the file. Last_y indicates the maximum y coordinate of the - * screen (which is usually SCREENMAX). - * - * A few strings must be initialized by hand before compiling mined. - * These string are enter_string, which is printed upon entering mined, - * rev_video (turn on reverse video), normal_video, rev_scroll (perform a - * reverse scroll) and pos_string. The last string should hold the - * absolute position string to be printed for cursor motion. The #define - * X_PLUS and Y_PLUS should contain the characters to be added to the - * coordinates x and y (both starting at 0) to finish cursor positioning. - * - * 3.2 Starting up. - * - * Mined can be called with or without argument and the function - * load_file () is called with these arguments. load_file () checks - * if the file exists if it can be read and if it is writable and - * sets the writable flag accordingly. If the file can be read, - * load_file () reads a line from the file and stores this line into - * a structure by calling install_line () and line_insert () which - * installs the line into the double linked list, until the end of the - * file is reached. - * Lines are read by the function get_line (), which buffers the - * reading in blocks of SCREEN_SIZE. Load_file () also initializes the - * LINE *variables described above. - * - * 3.3 Moving around. - * - * Several commands are implemented for moving through the file. - * Moving up (UP), down (DN) left (LF) and right (RT) are done by the - * arrow keys. Moving one line below the screen scrolls the screen one - * line up. Moving one line above the screen scrolls the screen one line - * down. The functions forward_scroll () and reverse_scroll () take care - * of that. - * Several other move functions exist: move to begin of line (BL), end of - * line (EL) top of screen (HIGH), bottom of screen (LOW), top of file - * (HO), end of file (EF), scroll one page down (PD), scroll one page up - * (PU), scroll one line down (SD), scroll one line up (SU) and move to a - * certain line number (GOTO). - * Two functions called MN () and MP () each move one word further or - * backwards. A word is a number of non-blanks seperated by a space, a - * tab or a linefeed. - * - * 3.4 Modifying text. - * - * The modifying commands can be separated into two modes. The first - * being inserting text, and the other deleting text. Two functions are - * created for these purposes: insert () and delete (). Both are capable - * of deleting or inserting large amounts of text as well as one - * character. Insert () must be given the line and location at which - * the text must be inserted. Is doesn't make any difference whether this - * text contains linefeeds or not. Delete () must be given a pointer to - * the start line, a pointer from where deleting should start on that - * line and the same information about the end position. The last - * character of the file will never be deleted. Delete () will make the - * necessary changes to the screen after deleting, but insert () won't. - * The functions for modifying text are: insert one char (S), insert a - * file (file_insert (fd)), insert a linefeed and put cursor back to - * end of line (LIB), delete character under the cursor (DCC), delete - * before cursor (even linefeed) (DPC), delete next word (DNW), delete - * previous word (DPC) and delete to end of line (if the cursor is at - * a linefeed delete line) (DLN). - * - * 3.5 Yanking. - * - * A few utilities are provided for yanking pieces of text. The function - * MA () marks the current position in the file. This is done by setting - * LINE *mark_line and char *mark_text to the current position. Yanking - * of text can be done in two modes. The first mode just copies the text - * from the mark to the current position (or visa versa) into a buffer - * (YA) and the second also deletes the text (DT). Both functions call - * the function set_up () with the delete flag on or off. Set_up () - * checks if the marked position is still a valid one (by using - * check_mark () and legal ()), and then calls the function yank () with - * a start and end position in the file. This function copies the text - * into a scratch_file as indicated by the variable yank_file. This - * scratch_file is made uniq by the function scratch_file (). At the end - * of copying yank will (if necessary) delete the text. A global flag - * called yank_status keeps track of the buffer (or file) status. It is - * initialized on NOT_VALID and set to EMPTY (by set_up ()) or VALID (by - * yank ()). Several things can be done with the buffer. It can be - * inserted somewhere else in the file (PT) or it can be copied into - * another file (WB), which will be prompted for. - * - * 3.6 Search and replace routines. - * - * Searching for strings and replacing strings are done by regular - * expressions. For any expression the function compile () is called - * with as argument the expression to compile. Compile () returns a - * pointer to a structure which looks like this: - * - * typedef struct regex { - * union { - * char *err_mess; - * int *expression; - * } result; - * char status; - * char *start_ptr; - * char *end_ptr; - * } REGEX; - * - * If something went wrong during compiling (e.g. an illegal expression - * was given), the function reg_error () is called, which sets the status - * field to REG_ERROR and the err_mess field to the error message. If the - * match must be anchored at the beginning of the line (end of line), the - * status field is set to BEGIN_LINE (END_LINE). If none of these special - * cases are true, the field is set to 0 and the function finished () is - * called. Finished () allocates space to hold the compiled expression - * and copies this expression into the expression field of the union - * (bcopy ()). Matching is done by the routines match() and line_check(). - * Match () takes as argument the REGEX *program, a pointer to the - * startposition on the current line, and a flag indicating FORWARD or - * REVERSE search. Match () checks out the whole file until a match is - * found. If match is found it returns a pointer to the line in which the - * match was found else it returns a NIL_LINE. Line_check () takes the - * same arguments, but return either MATCH or NO_MATCH. - * During checking, the start_ptr and end_ptr fields of the REGEX - * structure are assigned to the start and end of the match. - * Both functions try to find a match by walking through the line - * character by character. For each possibility, the function - * check_string () is called with as arguments the REGEX *program and the - * string to search in. It starts walking through the expression until - * the end of the expression or the end of the string is reached. - * Whenever a * is encountered, this position of the string is marked, - * the maximum number of matches are performed and the function star () - * is called in order to try to find the longest match possible. Star () - * takes as arguments the REGEX program, the current position of the - * string, the marked position and the current position of the expression - * Star () walks from the current position of the string back to the - * marked position, and calls string_check () in order to find a match. - * It returns MATCH or NO_MATCH, just as string_check () does. - * Searching is now easy. Both search routines (forward (SF) and - * backwards search (SR)) call search () with an apropiate message and a - * flag indicating FORWARD or REVERSE search. Search () will get an - * expression from the user by calling get_expression(). Get_expression() - * returns a pointer to a REGEX structure or NIL_REG upon errors and - * prompts for the expression. If no expression if given, the previous is - * used instead. After that search will call match (), and if a match is - * found, we can move to that place in the file by the functions find_x() - * and find_y () which will find display the match on the screen. - * Replacing can be done in two ways. A global replace (GR) or a line - * replace (LR). Both functions call change () with a message an a flag - * indicating global or line replacement. Change () will prompt for the - * expression and for the replacement. Every & in the replacement pattern - * means substitute the match instead. An & can be escaped by a \. When - * a match is found, the function substitute () will perform the - * substitution. - * - * 3.6 Miscellaneous commands. - * - * A few commands haven't be discussed yet. These are redraw the screen - * (RD) fork a shell (SH), print file status (FS), write file to disc - * (WT), insert a file at current position (IF), leave editor (XT) and - * visit another file (VI). The last two functions will check if the file - * has been modified. If it has, they will ask if you want to save the - * file by calling ask_save (). - * The function ESC () will repeat a command n times. It will prompt for - * the number. Aborting the loop can be done by sending the ^\ signal. - * - * 3.7 Utility functions. - * - * Several functions exists for internal use. First allocation routines: - * alloc (bytes) and newline () will return a pointer to free data space - * if the given size. If there is no more memory available, the function - * panic () is called. - * Signal handling: The only signal that can be send to mined is the - * SIGQUIT signal. This signal, functions as a general abort command. - * Mined will abort if the signal is given during the main loop. The - * function abort_mined () takes care of that. - * Panic () is a function with as argument a error message. It will print - * the message and the error number set by the kernel (errno) and will - * ask if the file must be saved or not. It resets the terminal - * (raw_mode ()) and exits. - * String handling routines like copy_string(to, from), length_of(string) - * and build_string (buffer, format, arg1, arg2, ...). The latter takes - * a description of the string out out the format field and puts the - * result in the buffer. (It works like printf (3), but then into a - * string). The functions status_line (string1, string2), error (string1, - * string2), clear_status () and bottom_line () all print information on - * the status line. - * Get_string (message, buffer) reads a string and getchar () reads one - * character from the terminal. - * Num_out ((long) number) prints the number into a 11 digit field - * without leading zero's. It returns a pointer to the resulting string. - * File_status () prints all file information on the status line. - * Set_cursor (x, y) prints the string to put the cursor at coordinates - * x and y. - * Output is done by four functions: writeline(fd,string), clear_buffer() - * write_char (fd, c) and flush_buffer (fd). Three defines are provided - * to write on filedescriptor STD_OUT (terminal) which is used normally: - * string_print (string), putchar (c) and flush (). All these functions - * use the global I/O buffer screen and the global index for this array - * called out_count. In this way I/O can be buffered, so that reads or - * writes can be done in blocks of SCREEN_SIZE size. - * The following functions all handle internal line maintenance. The - * function proceed (start_line, count) returns the count'th line after - * start_line. If count is negative, the count'th line before the - * start_line is returned. If header or tail is encountered then that - * will be returned. Display (x, y, start_line, count) displays count - * lines starting at coordinates [x, y] and beginning at start_line. If - * the header or tail is encountered, empty lines are displayed instead. - * The function reset (head_line, ny) reset top_line, last_y, bot_line, - * cur_line and y-coordinate. This is not a neat way to do the - * maintenance, but it sure saves a lot of code. It is usually used in - * combination with display (). - * Put_line(line, offset, clear_line), prints a line (skipping characters - * according to the line->shift_size field) until XBREAK - offset - * characters are printed or a '\n' is encountered. If clear_line is - * TRUE, spaces are printed until XBREAK - offset characters. - * Line_print (line) is a #define from put_line (line, 0, TRUE). - * Moving is done by the functions move_to (x, y), move_addres (address) - * and move (x, adress, y). This function is the most important one in - * mined. New_y must be between 0 and last_y, new_x can be about - * anything, address must be a pointer to an character on the current - * line (or y). Move_to () first adjust the y coordinate together with - * cur_line. If an address is given, it finds the corresponding - * x-coordinate. If an new x-coordinate was given, it will try to locate - * the corresponding character. After that it sets the shift_count field - * of cur_line to an apropiate number according to new_x. The only thing - * left to do now is to assign the new values to cur_line, cur_text, x - * and y. - * - * 4. Summary of commands. - * - * CURSOR MOTION - * up-arrow Move cursor 1 line up. At top of screen, reverse scroll - * down-arrow Move cursor 1 line down. At bottom, scroll forward. - * left-arrow Move cursor 1 character left or to end of previous line - * right-arrow Move cursor 1 character right or to start of next line - * CTRL-A Move cursor to start of current line - * CTRL-Z Move cursor to end of current line - * CTRL-^ Move cursor to top of screen - * CTRL-_ Move cursor to bottom of screen - * CTRL-F Forward to start of next word (even to next line) - * CTRL-B Backward to first character of previous word - * - * SCREEN MOTION - * Home key Move cursor to first character of file - * End key Move cursor to last character of file - * PgUp Scroll backward 1 page. Bottom line becomes top line - * PgD Scroll backward 1 page. Top line becomes bottom line - * CTRL-D Scroll screen down one line (reverse scroll) - * CTRL-U Scroll screen up one line (forward scroll) - * - * MODIFYING TEXT - * ASCII char Self insert character at cursor - * tab Insert tab at cursor - * backspace Delete the previous char (left of cursor), even line feed - * Del Delete the character under the cursor - * CTRL-N Delete next word - * CTRL-P Delete previous word - * CTRL-O Insert line feed at cursor and back up 1 character - * CTRL-T Delete tail of line (cursor to end); if empty, delete line - * CTRL-@ Set the mark (remember the current location) - * CTRL-K Delete text from the mark to current position save on file - * CTRL-C Save the text from the mark to the current position - * CTRL-Y Insert the contents of the save file at current position - * CTRL-Q Insert the contents of the save file into a new file - * CTRL-G Insert a file at the current position - * - * MISCELLANEOUS - * CTRL-E Erase and redraw the screen - * CTRL-V Visit file (read a new file); complain if old one changed - * CTRL-W Write the current file back to the disk - * numeric + Search forward (prompt for regular expression) - * numeric - Search backward (prompt for regular expression) - * numeric 5 Print the current status of the file - * CTRL-R (Global) Replace str1 by str2 (prompts for each string) - * CTRL-L (Line) Replace string1 by string2 - * CTRL-S Fork off a shell and wait for it to finish - * CTRL-X EXIT (prompt if file modified) - * CTRL-] Go to a line. Prompts for linenumber - * CTRL-\ Abort whatever editor was doing and start again - * escape key Repeat a command count times; (prompts for count) - */ - -/* ======================================================================== * - * Utilities * - * ======================================================================== */ - -#include "mined.h" -#include -#include -#include -#include -#include -#include -#if __STDC__ -#include -#else -#include -#endif - -extern int errno; -int ymax = YMAX; -int screenmax = SCREENMAX; - - -/* - * Print file status. - */ -void FS() -{ - fstatus(file_name[0] ? "" : "[buffer]", -1L); -} - -/* - * Visit (edit) another file. If the file has been modified, ask the user if - * he wants to save it. - */ -void VI() -{ - char new_file[LINE_LEN]; /* Buffer to hold new file name */ - - if (modified == TRUE && ask_save() == ERRORS) - return; - -/* Get new file name */ - if (get_file("Visit file:", new_file) == ERRORS) - return; - -/* Free old linked list, initialize global variables and load new file */ - initialize(); -#ifdef UNIX - tputs(CL, 0, _putchar); -#else - string_print (enter_string); -#endif /* UNIX */ - load_file(new_file[0] == '\0' ? NIL_PTR : new_file); -} - -/* - * Write file in core to disc. - */ -int WT() -{ - register LINE *line; - register long count = 0L; /* Nr of chars written */ - char file[LINE_LEN]; /* Buffer for new file name */ - int fd; /* Filedescriptor of file */ - - if (modified == FALSE) { - error ("Write not necessary.", NIL_PTR); - return FINE; - } - -/* Check if file_name is valid and if file can be written */ - if (file_name[0] == '\0' || writable == FALSE) { - if (get_file("Enter file name:", file) != FINE) - return ERRORS; - copy_string(file_name, file); /* Save file name */ - } - if ((fd = creat(file_name, 0644)) < 0) { /* Empty file */ - error("Cannot create ", file_name); - writable = FALSE; - return ERRORS; - } - else - writable = TRUE; - - clear_buffer(); - - status_line("Writing ", file_name); - for (line = header->next; line != tail; line = line->next) { - if (line->shift_count & DUMMY) { - if (line->next == tail && line->text[0] == '\n') - continue; - } - if (writeline(fd, line->text) == ERRORS) { - count = -1L; - break; - } - count += (long) length_of(line->text); - } - - if (count > 0L && flush_buffer(fd) == ERRORS) - count = -1L; - - (void) close(fd); - - if (count == -1L) - return ERRORS; - - modified = FALSE; - rpipe = FALSE; /* File name is now assigned */ - -/* Display how many chars (and lines) were written */ - fstatus("Wrote", count); - return FINE; -} - -/* Call WT and discard value returned. */ -void XWT() -{ - (void) WT(); -} - - - -/* - * Call an interactive shell. - */ -void SH() -{ - register int w; - int pid, status; - char *shell; - - if ((shell = getenv("SHELL")) == NIL_PTR) shell = "/bin/sh"; - - switch (pid = fork()) { - case -1: /* Error */ - error("Cannot fork.", NIL_PTR); - return; - case 0: /* This is the child */ - set_cursor(0, ymax); - putchar('\n'); - flush(); - raw_mode(OFF); - if (rpipe) { /* Fix stdin */ - close (0); - if (open("/dev/tty", 0) < 0) - exit (126); - } - execl(shell, shell, (char *) 0); - exit(127); /* Exit with 127 */ - default : /* This is the parent */ - signal(SIGINT, SIG_IGN); - signal(SIGQUIT, SIG_IGN); - do { - w = wait(&status); - } while (w != -1 && w != pid); - } - - raw_mode(ON); - RD(); - - if ((status >> 8) == 127) /* Child died with 127 */ - error("Cannot exec ", shell); - else if ((status >> 8) == 126) - error("Cannot open /dev/tty as fd #0", NIL_PTR); -} - -/* - * Proceed returns the count'th line after `line'. When count is negative - * it returns the count'th line before `line'. When the next (previous) - * line is the tail (header) indicating EOF (tof) it stops. - */ -LINE *proceed(line, count) -register LINE *line; -register int count; -{ - if (count < 0) - while (count++ < 0 && line != header) - line = line->prev; - else - while (count-- > 0 && line != tail) - line = line->next; - return line; -} - -/* - * Show concatenation of s1 and s2 on the status line (bottom of screen) - * If revfl is TRUE, turn on reverse video on both strings. Set stat_visible - * only if bottom_line is visible. - */ -int bottom_line(revfl, s1, s2, inbuf, statfl) -FLAG revfl; -char *s1, *s2; -char *inbuf; -FLAG statfl; -{ - int ret = FINE; - char buf[LINE_LEN]; - register char *p = buf; - - *p++ = ' '; - if (s1 != NIL_PTR) - while (*p = *s1++) - p++; - if (s2 != NIL_PTR) - while (*p = *s2++) - p++; - *p++ = ' '; - *p++ = 0; - - if (revfl == ON && stat_visible == TRUE) - clear_status (); - set_cursor(0, ymax); - if (revfl == ON) { /* Print rev. start sequence */ -#ifdef UNIX - tputs(SO, 0, _putchar); -#else - string_print(rev_video); -#endif /* UNIX */ - stat_visible = TRUE; - } - else /* Used as clear_status() */ - stat_visible = FALSE; - - string_print(buf); - - if (inbuf != NIL_PTR) - ret = input(inbuf, statfl); - - /* Print normal video */ -#ifdef UNIX - tputs(SE, 0, _putchar); - tputs(CE, 0, _putchar); -#else - string_print(normal_video); - string_print(blank_line); /* Clear the rest of the line */ -#endif /* UNIX */ - if (inbuf != NIL_PTR) - set_cursor(0, ymax); - else - set_cursor(x, y); /* Set cursor back to old position */ - flush(); /* Perform the actual write */ - if (ret != FINE) - clear_status(); - return ret; -} - -/* - * Count_chars() count the number of chars that the line would occupy on the - * screen. Counting starts at the real x-coordinate of the line. - */ -int count_chars(line) -LINE *line; -{ - register int cnt = get_shift(line->shift_count) * -SHIFT_SIZE; - register char *textp = line->text; - -/* Find begin of line on screen */ - while (cnt < 0) { - if (is_tab(*textp++)) - cnt = tab(cnt); - else - cnt++; - } - -/* Count number of chars left */ - cnt = 0; - while (*textp != '\n') { - if (is_tab(*textp++)) - cnt = tab(cnt); - else - cnt++; - } - return cnt; -} - -/* - * Move to coordinates nx, ny at screen. The caller must check that scrolling - * is not needed. - * If new_x is lower than 0 or higher than XBREAK, move_to() will check if - * the line can be shifted. If it can it sets(or resets) the shift_count field - * of the current line accordingly. - * Move also sets cur_text to the right char. - * If we're moving to the same x coordinate, try to move the the x-coordinate - * used on the other previous call. - */ -void move(new_x, new_address, new_y) -register int new_x; -int new_y; -char *new_address; -{ - register LINE *line = cur_line; /* For building new cur_line */ - int shift = 0; /* How many shifts to make */ - static int rel_x = 0; /* Remember relative x position */ - int tx = x; - -/* Check for illegal values */ - if (new_y < 0 || new_y > last_y) - return; - -/* Adjust y-coordinate and cur_line */ - if (new_y < y) - while (y != new_y) { - y--; - line = line->prev; - } - else - while (y != new_y) { - y++; - line = line->next; - } - -/* Set or unset relative x-coordinate */ - if (new_address == NIL_PTR) { - new_address = find_address(line, (new_x == x) ? rel_x : new_x , &tx); - if (new_x != x) - rel_x = tx; - new_x = tx; - } - else - rel_x = new_x = find_x(line, new_address); - -/* Adjust shift_count if new_x lower than 0 or higher than XBREAK */ - if (new_x < 0 || new_x >= XBREAK) { - if (new_x > XBREAK || (new_x == XBREAK && *new_address != '\n')) - shift = (new_x - XBREAK) / SHIFT_SIZE + 1; - else { - shift = new_x / SHIFT_SIZE; - if (new_x % SHIFT_SIZE) - shift--; - } - - if (shift != 0) { - line->shift_count += shift; - new_x = find_x(line, new_address); - set_cursor(0, y); - line_print(line); - rel_x = new_x; - } - } - -/* Assign and position cursor */ - x = new_x; - cur_text = new_address; - cur_line = line; - set_cursor(x, y); -} - -/* - * Find_x() returns the x coordinate belonging to address. - * (Tabs are expanded). - */ -int find_x(line, address) -LINE *line; -char *address; -{ - register char *textp = line->text; - register int nx = get_shift(line->shift_count) * -SHIFT_SIZE; - - while (textp != address && *textp != '\0') { - if (is_tab(*textp++)) /* Expand tabs */ - nx = tab(nx); - else - nx++; - } - return nx; -} - -/* - * Find_address() returns the pointer in the line with offset x_coord. - * (Tabs are expanded). - */ -char *find_address(line, x_coord, old_x) -LINE *line; -int x_coord; -int *old_x; -{ - register char *textp = line->text; - register int tx = get_shift(line->shift_count) * -SHIFT_SIZE; - - while (tx < x_coord && *textp != '\n') { - if (is_tab(*textp)) { - if (*old_x - x_coord == 1 && tab(tx) > x_coord) - break; /* Moving left over tab */ - else - tx = tab(tx); - } - else - tx++; - textp++; - } - - *old_x = tx; - return textp; -} - -/* - * Length_of() returns the number of characters int the string `string' - * excluding the '\0'. - */ -int length_of(string) -register char *string; -{ - register int count = 0; - - if (string != NIL_PTR) { - while (*string++ != '\0') - count++; - } - return count; -} - -/* - * Copy_string() copies the string `from' into the string `to'. `To' must be - * long enough to hold `from'. - */ -void copy_string(to, from) -register char *to; -register char *from; -{ - while (*to++ = *from++) - ; -} - -/* - * Reset assigns bot_line, top_line and cur_line according to `head_line' - * which must be the first line of the screen, and an y-coordinate, - * which will be the current y-coordinate (if it isn't larger than last_y) - */ -void reset(head_line, screen_y) -LINE *head_line; -int screen_y; -{ - register LINE *line; - - top_line = line = head_line; - -/* Search for bot_line (might be last line in file) */ - for (last_y = 0; last_y < nlines - 1 && last_y < screenmax - && line->next != tail; last_y++) - line = line->next; - - bot_line = line; - y = (screen_y > last_y) ? last_y : screen_y; - -/* Set cur_line according to the new y value */ - cur_line = proceed(top_line, y); -} - -/* - * Set cursor at coordinates x, y. - */ -void set_cursor(nx, ny) -int nx, ny; -{ -#ifdef UNIX - extern char *tgoto(); - - tputs(tgoto(CM, nx, ny), 0, _putchar); -#else - char text_buffer[10]; - - build_string(text_buffer, pos_string, ny+1, nx+1); - string_print(text_buffer); -#endif /* UNIX */ -} - -/* - * Routine to open terminal when mined is used in a pipeline. - */ -void open_device() -{ - if ((input_fd = open("/dev/tty", 0)) < 0) - panic("Cannot open /dev/tty for read"); -} - -/* - * Getchar() reads one character from the terminal. The character must be - * masked with 0377 to avoid sign extension. - */ -int getchar() -{ -#ifdef UNIX - return (_getchar() & 0377); -#else - char c; - - if (read(input_fd, &c, 1) != 1 && quit == FALSE) - panic("Can't read one char from fd #0"); - - return c & 0377; -#endif /* UNIX */ -} - -/* - * Display() shows count lines on the terminal starting at the given - * coordinates. When the tail of the list is encountered it will fill the - * rest of the screen with blank_line's. - * When count is negative, a backwards print from `line' will be done. - */ -void display(x_coord, y_coord, line, count) -int x_coord, y_coord; -register LINE *line; -register int count; -{ - set_cursor(x_coord, y_coord); - -/* Find new startline if count is negative */ - if (count < 0) { - line = proceed(line, count); - count = -count; - } - -/* Print the lines */ - while (line != tail && count-- >= 0) { - line_print(line); - line = line->next; - } - -/* Print the blank lines (if any) */ - if (loading == FALSE) { - while (count-- >= 0) { -#ifdef UNIX - tputs(CE, 0, _putchar); -#else - string_print(blank_line); -#endif /* UNIX */ - putchar('\n'); - } - } -} - -/* - * Write_char does a buffered output. - */ -int write_char(fd, c) -int fd; -char c; -{ - screen [out_count++] = c; - if (out_count == SCREEN_SIZE) /* Flush on SCREEN_SIZE chars */ - return flush_buffer(fd); - return FINE; -} - -/* - * Writeline writes the given string on the given filedescriptor. - */ -int writeline(fd, text) -register int fd; -register char *text; -{ - while(*text) - if (write_char(fd, *text++) == ERRORS) - return ERRORS; - return FINE; -} - -/* - * Put_line print the given line on the standard output. If offset is not zero - * printing will start at that x-coordinate. If the FLAG clear_line is TRUE, - * then (screen) line will be cleared when the end of the line has been - * reached. - */ -void put_line(line, offset, clear_line) -LINE *line; /* Line to print */ -int offset; /* Offset to start */ -FLAG clear_line; /* Clear to eoln if TRUE */ -{ - register char *textp = line->text; - register int count = get_shift(line->shift_count) * -SHIFT_SIZE; - int tab_count; /* Used in tab expansion */ - -/* Skip all chars as indicated by the offset and the shift_count field */ - while (count < offset) { - if (is_tab(*textp++)) - count = tab(count); - else - count++; - } - - while (*textp != '\n' && count < XBREAK) { - if (is_tab(*textp)) { /* Expand tabs to spaces */ - tab_count = tab(count); - while (count < XBREAK && count < tab_count) { - count++; - putchar(' '); - } - textp++; - } - else { - if (*textp >= '\01' && *textp <= '\037') { -#ifdef UNIX - tputs(SO, 0, _putchar); -#else - string_print (rev_video); -#endif /* UNIX */ - putchar(*textp++ + '\100'); -#ifdef UNIX - tputs(SE, 0, _putchar); -#else - string_print (normal_video); -#endif /* UNIX */ - } - else - putchar(*textp++); - count++; - } - } - -/* If line is longer than XBREAK chars, print the shift_mark */ - if (count == XBREAK && *textp != '\n') - putchar(textp[1]=='\n' ? *textp : SHIFT_MARK); - -/* Clear the rest of the line is clear_line is TRUE */ - if (clear_line == TRUE) { -#ifdef UNIX - tputs(CE, 0, _putchar); -#else - string_print(blank_line); -#endif /* UNIX */ - putchar('\n'); - } -} - -/* - * Flush the I/O buffer on filedescriptor fd. - */ -int flush_buffer(fd) -int fd; -{ - if (out_count <= 0) /* There is nothing to flush */ - return FINE; -#ifdef UNIX - if (fd == STD_OUT) { - printf("%.*s", out_count, screen); - _flush(); - } - else -#endif /* UNIX */ - if (write(fd, screen, out_count) != out_count) { - bad_write(fd); - return ERRORS; - } - clear_buffer(); /* Empty buffer */ - return FINE; -} - -/* - * Bad_write() is called when a write failed. Notify the user. - */ -void bad_write(fd) -int fd; -{ - if (fd == STD_OUT) /* Cannot write to terminal? */ - exit(1); - - clear_buffer(); - build_string(text_buffer, "Command aborted: %s (File incomplete)", - (errno == ENOSPC || errno == -ENOSPC) ? - "No space on device" : "Write error"); - error(text_buffer, NIL_PTR); -} - -/* - * Catch the SIGQUIT signal (^\) send to mined. It turns on the quitflag. - */ -void catch(sig) -int sig; -{ -/* Reset the signal */ - signal(SIGQUIT, catch); - quit = TRUE; -} - -/* - * Abort_mined() will leave mined. Confirmation is asked first. - */ -void abort_mined() -{ - quit = FALSE; - -/* Ask for confirmation */ - status_line("Really abort? ", NIL_PTR); - if (getchar() != 'y') { - clear_status(); - return; - } - -/* Reset terminal */ - raw_mode(OFF); - set_cursor(0, ymax); - putchar('\n'); - flush(); -#ifdef UNIX - abort(); -#else - exit(1); -#endif /* UNIX */ -} - -#define UNDEF _POSIX_VDISABLE - -/* - * Set and reset tty into CBREAK or old mode according to argument `state'. It - * also sets all signal characters (except for ^\) to UNDEF. ^\ is caught. - */ -void raw_mode(state) -FLAG state; -{ - static struct termios old_tty; - static struct termios new_tty; - - if (state == OFF) { - tcsetattr(input_fd, TCSANOW, &old_tty); - return; - } - -/* Save old tty settings */ - tcgetattr(input_fd, &old_tty); - -/* Set tty to CBREAK mode */ - tcgetattr(input_fd, &new_tty); - new_tty.c_lflag &= ~(ICANON|ECHO|ECHONL); - new_tty.c_iflag &= ~(IXON|IXOFF); - -/* Unset signal chars, leave only SIGQUIT set to ^\ */ - new_tty.c_cc[VINTR] = new_tty.c_cc[VSUSP] = UNDEF; - new_tty.c_cc[VQUIT] = '\\' & 037; - signal(SIGQUIT, catch); /* Which is caught */ - - tcsetattr(input_fd, TCSANOW, &new_tty); -} - -/* - * Panic() is called with an error number and a message. It is called when - * something unrecoverable has happened. - * It writes the message to the terminal, resets the tty and exits. - * Ask the user if he wants to save his file. - */ -void panic(message) -register char *message; -{ - extern char yank_file[]; - -#ifdef UNIX - tputs(CL, 0, _putchar); - build_string(text_buffer, "%s\nError code %d\n", message, errno); -#else - build_string(text_buffer, "%s%s\nError code %d\n", enter_string, message, errno); -#endif /* UNIX */ - (void) write(STD_OUT, text_buffer, length_of(text_buffer)); - - if (loading == FALSE) - XT(); /* Check if file can be saved */ - else - (void) unlink(yank_file); - raw_mode(OFF); - -#ifdef UNIX - abort(); -#else - exit(1); -#endif /* UNIX */ -} - -char *alloc(bytes) -int bytes; -{ - char *p; - - p = malloc((unsigned) bytes); - if (p == NIL_PTR) { - if (loading == TRUE) - panic("File too big."); - panic("Out of memory."); - } - return(p); -} - -void free_space(p) -char *p; -{ - free(p); -} - -/* ======================================================================== * - * Main loops * - * ======================================================================== */ - -/* The mapping between input codes and functions. */ - -void (*key_map[256])() = { /* map ASCII characters to functions */ - /* 000-017 */ MA, BL, MP, YA, SD, RD, MN, IF, DPC, S, S, DT, LR, S, DNW,LIB, - /* 020-037 */ DPW, WB, GR, SH, DLN, SU, VI, XWT, XT, PT, EL, ESC, I, GOTO, - HIGH, LOW, - /* 040-057 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 060-077 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 100-117 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 120-137 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 140-157 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 160-177 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, DCC, - /* 200-217 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 220-237 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 240-257 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 260-277 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 300-317 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 320-337 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 340-357 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, - /* 360-377 */ S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, -}; - -int nlines; /* Number of lines in file */ -LINE *header; /* Head of line list */ -LINE *tail; /* Last line in line list */ -LINE *cur_line; /* Current line in use */ -LINE *top_line; /* First line of screen */ -LINE *bot_line; /* Last line of screen */ -char *cur_text; /* Current char on current line in use */ -int last_y; /* Last y of screen. Usually SCREENMAX */ -char screen[SCREEN_SIZE]; /* Output buffer for "writes" and "reads" */ - -int x, y; /* x, y coordinates on screen */ -FLAG modified = FALSE; /* Set when file is modified */ -FLAG stat_visible; /* Set if status_line is visible */ -FLAG writable; /* Set if file cannot be written */ -FLAG loading; /* Set if we are loading a file. */ -FLAG quit = FALSE; /* Set when quit character is typed */ -FLAG rpipe = FALSE; /* Set if file should be read from stdin */ -int input_fd = 0; /* Fd for command input */ -int out_count; /* Index in output buffer */ -char file_name[LINE_LEN]; /* Name of file in use */ -char text_buffer[MAX_CHARS]; /* Buffer for modifying text */ - -/* Escape sequences. */ -#ifdef UNIX -char *CE, *VS, *SO, *SE, *CL, *AL, *CM; -#else -char *enter_string = "\033[H\033[J"; /* String printed on entering mined */ -char *pos_string = "\033[%d;%dH"; /* Absolute cursor position */ -char *rev_scroll = "\033M"; /* String for reverse scrolling */ -char *rev_video = "\033[7m"; /* String for starting reverse video */ -char *normal_video = "\033[m"; /* String for leaving reverse video */ -char *blank_line = "\033[K"; /* Clear line to end */ -#endif /* UNIX */ - -/* - * Yank variables. - */ -FLAG yank_status = NOT_VALID; /* Status of yank_file */ -char yank_file[] = "/tmp/mined.XXXXXX"; -long chars_saved; /* Nr of chars in buffer */ - -/* - * Initialize is called when a another file is edited. It free's the allocated - * space and sets modified back to FALSE and fixes the header/tail pointer. - */ -void initialize() -{ - register LINE *line, *next_line; - -/* Delete the whole list */ - for (line = header->next; line != tail; line = next_line) { - next_line = line->next; - free_space(line->text); - free_space((char*)line); - } - -/* header and tail should point to itself */ - line->next = line->prev = line; - x = y = 0; - rpipe = modified = FALSE; -} - -/* - * Basename() finds the absolute name of the file out of a given path_name. - */ -char *basename(path) -char *path; -{ - register char *ptr = path; - register char *last = NIL_PTR; - - while (*ptr != '\0') { - if (*ptr == '/') - last = ptr; - ptr++; - } - if (last == NIL_PTR) - return path; - if (*(last + 1) == '\0') { /* E.g. /usr/tmp/pipo/ */ - *last = '\0'; - return basename(path);/* Try again */ - } - return last + 1; -} - -/* - * Load_file loads the file `file' into core. If file is a NIL_PTR or the file - * couldn't be opened, just some initializations are done, and a line consisting - * of a `\n' is installed. - */ -void load_file(file) -char *file; -{ - register LINE *line = header; - register int len; - long nr_of_chars = 0L; - int fd = -1; /* Filedescriptor for file */ - - nlines = 0; /* Zero lines to start with */ - -/* Open file */ - writable = TRUE; /* Benefit of the doubt */ - if (file == NIL_PTR) { - if (rpipe == FALSE) - status_line("No file.", NIL_PTR); - else { - fd = 0; - file = "standard input"; - } - file_name[0] = '\0'; - } - else { - copy_string(file_name, file); /* Save file name */ - if (access(file, 0) < 0) /* Cannot access file. */ - status_line("New file ", file); - else if ((fd = open(file, 0)) < 0) - status_line("Cannot open ", file); - else if (access(file, 2) != 0) /* Set write flag */ - writable = FALSE; - } - -/* Read file */ - loading = TRUE; /* Loading file, so set flag */ - - if (fd >= 0) { - status_line("Reading ", file); - while ((len = get_line(fd, text_buffer)) != ERRORS) { - line = line_insert(line, text_buffer, len); - nr_of_chars += (long) len; - } - if (nlines == 0) /* The file was empty! */ - line = line_insert(line, "\n", 1); - clear_buffer(); /* Clear output buffer */ - cur_line = header->next; - fstatus("Read", nr_of_chars); - (void) close(fd); /* Close file */ - } - else /* Just install a "\n" */ - (void) line_insert(line, "\n", 1); - - reset(header->next, 0); /* Initialize pointers */ - -/* Print screen */ - display (0, 0, header->next, last_y); - move_to (0, 0); - flush(); /* Flush buffer */ - loading = FALSE; /* Stop loading, reset flag */ -} - - -/* - * Get_line reads one line from filedescriptor fd. If EOF is reached on fd, - * get_line() returns ERRORS, else it returns the length of the string. - */ -int get_line(fd, buffer) -int fd; -register char *buffer; -{ - static char *last = NIL_PTR; - static char *current = NIL_PTR; - static int read_chars; - register char *cur_pos = current; - char *begin = buffer; - - do { - if (cur_pos == last) { - if ((read_chars = read(fd, screen, SCREEN_SIZE)) <= 0) - break; - last = &screen[read_chars]; - cur_pos = screen; - } - if (*cur_pos == '\0') - *cur_pos = ' '; - } while ((*buffer++ = *cur_pos++) != '\n'); - - current = cur_pos; - if (read_chars <= 0) { - if (buffer == begin) - return ERRORS; - if (*(buffer - 1) != '\n') - if (loading == TRUE) /* Add '\n' to last line of file */ - *buffer++ = '\n'; - else { - *buffer = '\0'; - return NO_LINE; - } - } - - *buffer = '\0'; - return buffer - begin; -} - -/* - * Install_line installs the buffer into a LINE structure It returns a pointer - * to the allocated structure. - */ -LINE *install_line(buffer, length) -char *buffer; -int length; -{ - register LINE *new_line = (LINE *) alloc(sizeof(LINE)); - - new_line->text = alloc(length + 1); - new_line->shift_count = 0; - copy_string(new_line->text, buffer); - - return new_line; -} - -void main(argc, argv) -int argc; -char *argv[]; -{ -/* mined is the Minix editor. */ - - register int index; /* Index in key table */ - struct winsize winsize; - -#ifdef UNIX - get_term(); - tputs(VS, 0, _putchar); - tputs(CL, 0, _putchar); -#else - string_print(enter_string); /* Hello world */ -#endif /* UNIX */ - if (ioctl(STD_OUT, TIOCGWINSZ, &winsize) == 0 && winsize.ws_row != 0) { - ymax = winsize.ws_row - 1; - screenmax = ymax - 1; - } - - if (!isatty(0)) { /* Reading from pipe */ - if (argc != 1) { - write(2, "Cannot find terminal.\n", 22); - exit (1); - } - rpipe = TRUE; - modified = TRUE; /* Set modified so he can write */ - open_device(); - } - - raw_mode(ON); /* Set tty to appropriate mode */ - - header = tail = (LINE *) alloc(sizeof(LINE)); /* Make header of list*/ - header->text = NIL_PTR; - header->next = tail->prev = header; - -/* Load the file (if any) */ - if (argc < 2) - load_file(NIL_PTR); - else { - (void) get_file(NIL_PTR, argv[1]); /* Truncate filename */ - load_file(argv[1]); - } - - /* Main loop of the editor. */ - for (;;) { - index = getchar(); - if (stat_visible == TRUE) - clear_status(); - if (quit == TRUE) - abort_mined(); - else { /* Call the function for this key */ - (*key_map[index])(index); - flush(); /* Flush output (if any) */ - if (quit == TRUE) - quit = FALSE; - } - } - /* NOTREACHED */ -} - -/* ======================================================================== * - * Miscellaneous * - * ======================================================================== */ - -/* - * Redraw the screen - */ -void RD() -{ -/* Clear screen */ -#ifdef UNIX - tputs(VS, 0, _putchar); - tputs(CL, 0, _putchar); -#else - string_print(enter_string); -#endif /* UNIX */ - -/* Print first page */ - display(0, 0, top_line, last_y); - -/* Clear last line */ - set_cursor(0, ymax); -#ifdef UNIX - tputs(CE, 0, _putchar); -#else - string_print(blank_line); -#endif /* UNIX */ - move_to(x, y); -} - -/* - * Ignore this keystroke. - */ -void I() -{ -} - -/* - * Leave editor. If the file has changed, ask if the user wants to save it. - */ -void XT() -{ - if (modified == TRUE && ask_save() == ERRORS) - return; - - raw_mode(OFF); - set_cursor(0, ymax); - putchar('\n'); - flush(); - (void) unlink(yank_file); /* Might not be necessary */ - exit(0); -} - -void (*escfunc(c))() -int c; -{ -#if (CHIP == M68000) -#ifndef COMPAT - int ch; -#endif -#endif - if (c == '[') { - /* Start of ASCII escape sequence. */ - c = getchar(); -#if (CHIP == M68000) -#ifndef COMPAT - if ((c >= '0') && (c <= '9')) ch = getchar(); - /* ch is either a tilde or a second digit */ -#endif -#endif - switch (c) { - case 'H': return(HO); - case 'A': return(UP); - case 'B': return(DN); - case 'C': return(RT); - case 'D': return(LF); -#if (CHIP == M68000) -#ifndef COMPAT - /* F1 = ESC [ 1 ~ */ - /* F2 = ESC [ 2 ~ */ - /* F3 = ESC [ 3 ~ */ - /* F4 = ESC [ 4 ~ */ - /* F5 = ESC [ 5 ~ */ - /* F6 = ESC [ 6 ~ */ - /* F7 = ESC [ 17 ~ */ - /* F8 = ESC [ 18 ~ */ - case '1': - switch (ch) { - case '~': return(SF); - case '7': (void) getchar(); return(MA); - case '8': (void) getchar(); return(CTL); - } - case '2': return(SR); - case '3': return(PD); - case '4': return(PU); - case '5': return(FS); - case '6': return(EF); -#endif -#endif -#if (CHIP == INTEL) - case 'G': return(FS); - case 'S': return(SR); - case 'T': return(SF); - case 'U': return(PD); - case 'V': return(PU); - case 'Y': return(EF); -#endif - } - return(I); - } -#if (CHIP == M68000) -#ifdef COMPAT - if (c == 'O') { - /* Start of ASCII function key escape sequence. */ - switch (getchar()) { - case 'P': return(SF); - case 'Q': return(SR); - case 'R': return(PD); - case 'S': return(PU); - case 'T': return(FS); - case 'U': return(EF); - case 'V': return(MA); - case 'W': return(CTL); - } - } -#endif -#endif - return(I); -} - -/* - * ESC() wants a count and a command after that. It repeats the - * command count times. If a ^\ is given during repeating, stop looping and - * return to main loop. - */ -void ESC() -{ - register int count = 0; - register void (*func)(); - int index; - - index = getchar(); - while (index >= '0' && index <= '9' && quit == FALSE) { - count *= 10; - count += index - '0'; - index = getchar(); - } - if (count == 0) { - count = 1; - func = escfunc(index); - } else { - func = key_map[index]; - if (func == ESC) - func = escfunc(getchar()); - } - - if (func == I) { /* Function assigned? */ - clear_status(); - return; - } - - while (count-- > 0 && quit == FALSE) { - if (stat_visible == TRUE) - clear_status(); - (*func)(index); - flush(); - } - - if (quit == TRUE) /* Abort has been given */ - error("Aborted", NIL_PTR); -} - -/* - * Ask the user if he wants to save his file or not. - */ -int ask_save() -{ - register int c; - - status_line(file_name[0] ? basename(file_name) : "[buffer]" , - " has been modified. Save? (y/n)"); - - while((c = getchar()) != 'y' && c != 'n' && quit == FALSE) { - ring_bell(); - flush(); - } - - clear_status(); - - if (c == 'y') - return WT(); - - if (c == 'n') - return FINE; - - quit = FALSE; /* Abort character has been given */ - return ERRORS; -} - -/* - * Line_number() finds the line number we're on. - */ -int line_number() -{ - register LINE *line = header->next; - register int count = 1; - - while (line != cur_line) { - count++; - line = line->next; - } - - return count; -} - -/* - * Display a line telling how many chars and lines the file contains. Also tell - * whether the file is readonly and/or modified. - */ -void file_status(message, count, file, lines, writefl, changed) -char *message; -register long count; /* Contains number of characters in file */ -char *file; -int lines; -FLAG writefl, changed; -{ - register LINE *line; - char msg[LINE_LEN + 40];/* Buffer to hold line */ - char yank_msg[LINE_LEN];/* Buffer for msg of yank_file */ - - if (count < 0) /* Not valid. Count chars in file */ - for (line = header->next; line != tail; line = line->next) - count += length_of(line->text); - - if (yank_status != NOT_VALID) /* Append buffer info */ - build_string(yank_msg, " Buffer: %D char%s.", chars_saved, - (chars_saved == 1L) ? "" : "s"); - else - yank_msg[0] = '\0'; - - build_string(msg, "%s %s%s%s %d line%s %D char%s.%s Line %d", message, - (rpipe == TRUE && *message != '[') ? "standard input" : basename(file), - (changed == TRUE) ? "*" : "", - (writefl == FALSE) ? " (Readonly)" : "", - lines, (lines == 1) ? "" : "s", - count, (count == 1L) ? "" : "s", - yank_msg, line_number()); - - if (length_of(msg) + 1 > LINE_LEN - 4) { - msg[LINE_LEN - 4] = SHIFT_MARK; /* Overflow on status line */ - msg[LINE_LEN - 3] = '\0'; - } - status_line(msg, NIL_PTR); /* Print the information */ -} - -/* - * Build_string() prints the arguments as described in fmt, into the buffer. - * %s indicates an argument string, %d indicated an argument number. - */ -#if __STDC__ -void build_string(char *buf, char *fmt, ...) -{ -#else -void build_string(buf, fmt, va_alist) -char *buf, *fmt; -va_dcl -{ -#endif - va_list argptr; - char *scanp; - -#if __STDC__ - va_start(argptr, fmt); -#else - va_start(argptr); -#endif - - while (*fmt) { - if (*fmt == '%') { - fmt++; - switch (*fmt++) { - case 's' : - scanp = va_arg(argptr, char *); - break; - case 'd' : - scanp = num_out((long) va_arg(argptr, int)); - break; - case 'D' : - scanp = num_out((long) va_arg(argptr, long)); - break; - default : - scanp = ""; - } - while (*buf++ = *scanp++) - ; - buf--; - } - else - *buf++ = *fmt++; - } - va_end(argptr); - *buf = '\0'; -} - -/* - * Output an (unsigned) long in a 10 digit field without leading zeros. - * It returns a pointer to the first digit in the buffer. - */ -char *num_out(number) -long number; -{ - static char num_buf[11]; /* Buffer to build number */ - register long digit; /* Next digit of number */ - register long pow = 1000000000L; /* Highest ten power of long */ - FLAG digit_seen = FALSE; - int i; - - for (i = 0; i < 10; i++) { - digit = number / pow; /* Get next digit */ - if (digit == 0L && digit_seen == FALSE && i != 9) - num_buf[i] = ' '; - else { - num_buf[i] = '0' + (char) digit; - number -= digit * pow; /* Erase digit */ - digit_seen = TRUE; - } - pow /= 10L; /* Get next digit */ - } - for (i = 0; num_buf[i] == ' '; i++) /* Skip leading spaces */ - ; - return (&num_buf[i]); -} - -/* - * Get_number() read a number from the terminal. The last character typed in is - * returned. ERRORS is returned on a bad number. The resulting number is put - * into the integer the arguments points to. - */ -int get_number(message, result) -char *message; -int *result; -{ - register int index; - register int count = 0; - - status_line(message, NIL_PTR); - - index = getchar(); - if (quit == FALSE && (index < '0' || index > '9')) { - error("Bad count", NIL_PTR); - return ERRORS; - } - -/* Convert input to a decimal number */ - while (index >= '0' && index <= '9' && quit == FALSE) { - count *= 10; - count += index - '0'; - index = getchar(); - } - - if (quit == TRUE) { - clear_status(); - return ERRORS; - } - - *result = count; - return index; -} - -/* - * Input() reads a string from the terminal. When the KILL character is typed, - * it returns ERRORS. - */ -int input(inbuf, clearfl) -char *inbuf; -FLAG clearfl; -{ - register char *ptr; - register char c; /* Character read */ - - ptr = inbuf; - - *ptr = '\0'; - while (quit == FALSE) { - flush(); - switch (c = getchar()) { - case '\b' : /* Erase previous char */ - if (ptr > inbuf) { - ptr--; -#ifdef UNIX - tputs(SE, 0, _putchar); -#else - string_print(normal_video); -#endif /* UNIX */ - if (is_tab(*ptr)) - string_print(" \b\b\b \b\b"); - else - string_print(" \b\b \b"); -#ifdef UNIX - tputs(SO, 0, _putchar); -#else - string_print(rev_video); -#endif /* UNIX */ - string_print(" \b"); - *ptr = '\0'; - } - else - ring_bell(); - break; - case '\n' : /* End of input */ - /* If inbuf is empty clear status_line */ - return (ptr == inbuf && clearfl == TRUE) ? NO_INPUT :FINE; - default : /* Only read ASCII chars */ - if ((c >= ' ' && c <= '~') || c == '\t') { - *ptr++ = c; - *ptr = '\0'; - if (c == '\t') - string_print("^I"); - else - putchar(c); - string_print(" \b"); - } - else - ring_bell(); - } - } - quit = FALSE; - return ERRORS; -} - -/* - * Get_file() reads a filename from the terminal. Filenames longer than - * FILE_LENGHT chars are truncated. - */ -int get_file(message, file) -char *message, *file; -{ - char *ptr; - int ret; - - if (message == NIL_PTR || (ret = get_string(message, file, TRUE)) == FINE) { - if (length_of((ptr = basename(file))) > NAME_MAX) - ptr[NAME_MAX] = '\0'; - } - return ret; -} - -/* ======================================================================== * - * UNIX I/O Routines * - * ======================================================================== */ - -#ifdef UNIX -#undef putchar - -int _getchar() -{ - char c; - - if (read(input_fd, &c, 1) != 1 && quit == FALSE) - panic ("Cannot read 1 byte from input"); - return c & 0377; -} - -void _flush() -{ - (void) fflush(stdout); -} - -void _putchar(c) -char c; -{ - (void) write_char(STD_OUT, c); -} - -void get_term() -{ - static char termbuf[50]; - extern char *tgetstr(), *getenv(); - char *loc = termbuf; - char entry[1024]; - - if (tgetent(entry, getenv("TERM")) <= 0) { - printf("Unknown terminal.\n"); - exit(1); - } - - AL = tgetstr("al", &loc); - CE = tgetstr("ce", &loc); - VS = tgetstr("vs", &loc); - CL = tgetstr("cl", &loc); - SO = tgetstr("so", &loc); - SE = tgetstr("se", &loc); - CM = tgetstr("cm", &loc); - ymax = tgetnum("li") - 1; - screenmax = ymax - 1; - - if (!CE || !SO || !SE || !CL || !AL || !CM) { - printf("Sorry, no mined on this type of terminal\n"); - exit(1); - } -} -#endif /* UNIX */ 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_1.1_helloworld.c b/languages/cprogs/sec_1.1_helloworld.c index d677797d..a91aefbf 100644 --- a/languages/cprogs/sec_1.1_helloworld.c +++ b/languages/cprogs/sec_1.1_helloworld.c @@ -1,8 +1,8 @@ -/* First Program in KandR, the hello,world */ +/* First Program in K&R. print hello,world */ -#include -void main() +#include + +int main() { - printf("hello,world\n"); + printf("hello, world\n"); } - 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/java/AbstractClass.java b/languages/java/AbstractClass.java deleted file mode 100644 index 03bd7c0e..00000000 --- a/languages/java/AbstractClass.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Example 27 - Abstract Classes, Subclasses, and Overriding - */ -class AbstractClass { - - abstract class Vessel { - double contents; - abstract double capacity(); - void fill(double amount) { - contents = Math.min(contents + amount, capacity()); - } - } - - class Tank extends Vessel { - - double length, width, height; - - Tank(double length, double width, double height) { - this.length = length; - this.width = width; - this.height = height; - } - - double capacity() { - return length * width * height; - } - - public String toString() { - return "tank (" + length + ", " + width + ", " + height + ")"; - } - } - - class Cube extends Tank { - - Cube(double side) { - super(side, side, side); - } - - public String toString() { - return "cube (" + length + ")"; - } - } - - class Barrel extends Vessel { - double radius, height; - - Barrel(double radius, double height) { - this.radius = radius; - this.height = height; - } - - double capacity() { - return height * Math.PI * radius * radius; - } - - public String toString() { - return "barrel (" + radius + ", " + height + ")"; - } - } -} diff --git a/languages/java/AlignNumbers.java b/languages/java/AlignNumbers.java deleted file mode 100644 index 4faa724e..00000000 --- a/languages/java/AlignNumbers.java +++ /dev/null @@ -1,14 +0,0 @@ -import java.util.Random; - -/** - * Example 14 - Aligning Numbers in Columns using out.format - */ -class AlignNumbers { - public static void main(String[] args) { - Random rnd = new Random(); - for (int i = 0; i < 3; i++) - for (int j = 0; j <5; j++) - System.out.format("%4d", rnd.nextInt(1000)); - System.out.format("%n"); - } -} diff --git a/languages/java/AligningStrings.java b/languages/java/AligningStrings.java deleted file mode 100644 index 44d80293..00000000 --- a/languages/java/AligningStrings.java +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Example 13 - Aligning Strings Using String.format Method - */ -class AligningStrings { - public static void main(String[] args) { - String res = String.format("|%1$s|%1$15s|%1$-15s|", "Uthcode"); - System.out.println(res); - } -} diff --git a/languages/java/AllPathsTryCatchFinally.java b/languages/java/AllPathsTryCatchFinally.java deleted file mode 100644 index 93e42d35..00000000 --- a/languages/java/AllPathsTryCatchFinally.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Example 90 - All Paths Through a try-catch-finally Statement - */ -class AllPathsTryCatchFinally { - - public static void main(String[] args) throws Exception{ - System.out.println(m(Integer.parseInt(args[0]))); - } - - static String m(int a) throws Exception { - try { - System.out.println("try ..."); - if (a/100 == 2) return "returned from try"; - if (a/100 == 3) throw new Exception("thrown by try"); - if (a/100 == 4) throw new RuntimeException("thrown by a try"); - } catch (RuntimeException x) { - System.out.println("catch ..."); - if (a/10%10 == 2) return "returned from catch"; - if (a/10%10 == 3) throw new Exception("thrown by catch"); - } finally { - System.out.println("finally"); - if (a%10 == 2) return "returned from finally"; - if (a%10 == 3) throw new Exception("thrown by finally"); - } - return "terminated normally with " + a; - } -} diff --git a/languages/java/AnimatedCanvas.java b/languages/java/AnimatedCanvas.java deleted file mode 100644 index 9b502f08..00000000 --- a/languages/java/AnimatedCanvas.java +++ /dev/null @@ -1,35 +0,0 @@ -import javax.swing.*; -import java.awt.*; - -/** - * Example 95 - Graphic Animation Using the Runnable Interface - */ -class AnimatedCanvas extends Canvas implements Runnable{ - - AnimatedCanvas() { - Thread u = new Thread(this); - u.start(); - } - - @Override - public void run() { - for(;;){ - try { - Thread.sleep(100); - } catch (InterruptedException e) {} - repaint(); - } - } - - public void paint(Graphics g) { - g.drawString("Hello World", 200, 200); - } - - public static void main(String[] args) { - AnimatedCanvas animatedCanvas = new AnimatedCanvas(); - JFrame jp = new JFrame(); - jp.getContentPane().add(animatedCanvas, BorderLayout.CENTER); - jp.setSize(new Dimension(500,500)); - jp.setVisible(true); - } -} diff --git a/languages/java/ArithmeticOperators.java b/languages/java/ArithmeticOperators.java deleted file mode 100644 index 340551a4..00000000 --- a/languages/java/ArithmeticOperators.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Example 45 - Arithmetic Operators - */ -class ArithmeticOperators { - - public static void main(String[] args) { - int max = 2147483647; - int min = -2147483638; - System.out.println(max+1); - System.out.println(min-1); - System.out.print(10 / 3); - System.out.println(10/(-3)); - System.out.print(10 % 3); - System.out.println(10%(-3)); - System.out.print((-10) % 3); - System.out.println((-10) % (-3)); - } -} diff --git a/languages/java/ArrayAssignmentTypeCheck.java b/languages/java/ArrayAssignmentTypeCheck.java deleted file mode 100644 index 8872b8cd..00000000 --- a/languages/java/ArrayAssignmentTypeCheck.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Example 19 - Array Element Assignment Type Check at Run-Time - */ -public class ArrayAssignmentTypeCheck { - - public static void main(String[] args) { - Number[] a = new Integer[10]; - Double d = new Double(3.14); - Integer i = new Integer(117); - Number n = i; - a[0] = i; - a[1] = n; - // Results in a Runtime exception - try { - a[2] = d; - } catch (ArrayStoreException e) { - System.out.println("Caught an ArrayStoreException."); - } - } - -} diff --git a/languages/java/AssignmentNoCopyObjects.java b/languages/java/AssignmentNoCopyObjects.java deleted file mode 100644 index 39ca6fa4..00000000 --- a/languages/java/AssignmentNoCopyObjects.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Example 49 - Assignment Does Not Copy Objects - */ -class AssignmentNoCopyObjects { - - static class Point { - int x; - int y; - - Point(int x, int y) { - this.x = x; - this.y = y; - } - - void move(int x1, int y1) { - x += x1; - y += y1; - } - - public String toString() { - return "(" + x + ", " + y + ")"; - } - } - - public static void main(String[] args) { - // TODO: Senthil Kumaran decouple Point - Point p1 = new Point(10, 20); - System.out.println("p1 is " + p1); - Point p2 = p1; - p2.move(8, 8); - System.out.println("p2 is " + p2); - System.out.println("p1 is " + p1); - } - -} diff --git a/languages/java/AutoBoxingUnboxing.java b/languages/java/AutoBoxingUnboxing.java deleted file mode 100644 index 487a37e3..00000000 --- a/languages/java/AutoBoxingUnboxing.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Example 3 Automatic Boxing and Unboxing - */ -class AutoBoxingUnboxing { - - public static void main(String[] args) { - Boolean bb1 = false, bb2 = !bb1; // Boxing to false, true - Integer bi1 = 117; - Double bd1 = 1.2; - boolean b1 = bb1; - if (bb1) - System.out.println("Not true"); - int i1 = bi1 + 2; - // short s = bi1; - long l = bi1; - Integer bi2 = bi1 + 2; - Integer[] biarr = {2, 3, 5, 7, 11}; - int sum = 0; - for(Integer bi: biarr) - sum += bi; - for(int i: biarr) - sum += i; - int i = 1934; - Integer bi4 = i, bi5 = i; - - // Prints true true true flase; bi4 == bi5 is a reference comparison - System.out.format("%b %b %b %b\n", i==i, bi4==i, i==bi5, bi4==bi5); - Boolean bbn = null; - // boolean b = bbn; // compiles Okay but will fail at runtime - // if (bbn) - // System.out.println("Not True"); - Integer bin = null; - // Integer bi6 = bin + 2; // compiles Okay, but will fail at runtime - } -} diff --git a/languages/java/BinaryOutput.java b/languages/java/BinaryOutput.java deleted file mode 100644 index 5d5b3166..00000000 --- a/languages/java/BinaryOutput.java +++ /dev/null @@ -1,60 +0,0 @@ -import java.io.*; - -/** - * Example 147 - Binary Input and Output of Primitive Data - */ -class BinaryOutput { - - public static void main(String[] args) throws IOException { - DataOutputStream daos = new DataOutputStream(new FileOutputStream("tmp1.dat")); - writedata(daos); - daos.close(); - - DataInputStream dais = new DataInputStream(new FileInputStream("tmp1.dat")); - readdata(dais); - - RandomAccessFile raf = new RandomAccessFile("tmp2.dat", "rw"); - writedata(raf); - raf.seek(0); - readdata(raf); - } - - static void writedata(DataOutput out) throws IOException { - out.writeBoolean(true); - out.writeByte(120); - out.writeBytes("foo"); - out.writeBytes("fo"); - out.writeChar('A'); - out.writeChars("foo"); - out.writeDouble(300.1); - out.writeFloat(300.2F); - out.writeInt(1234); - out.writeLong(12345L); - out.writeShort(32000); - out.writeUTF("foo"); - out.writeByte(-1); - out.writeShort(-1); - } - - static void readdata(DataInput in) throws IOException { - byte[] buf1 = new byte[3]; - System.out.print(in.readBoolean()); - System.out.print(" " + in.readByte()); - in.readFully(buf1); - in.readFully(buf1, 0, 2); - System.out.print(" " + in.readChar()); - System.out.print(" " + in.readChar() + in.readChar() + in.readChar()); - System.out.print(" " + in.readDouble()); - System.out.print(" " + in.readFloat()); - System.out.print(" " + in.readInt()); - System.out.print(" " + in.readLong()); - System.out.print(" " + in.readShort()); - System.out.print(" " + in.readUTF()); - System.out.print(" " + in.readUTF()); - System.out.print(" " + in.readUnsignedByte()); - System.out.print(" " + in.readUnsignedShort()); - System.out.println(); - } - - -} diff --git a/languages/java/BinarySearchSortedArray.java b/languages/java/BinarySearchSortedArray.java deleted file mode 100644 index 965283fd..00000000 --- a/languages/java/BinarySearchSortedArray.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Example 73 - Binary Search of a Sorted Array using a While loop - */ -public class BinarySearchSortedArray { - - public static int binarySearch(double[] arr, double x) { - int a = 0, b = arr.length - 1; - - while (a <= b) { // Loop invariant: arr[a-1] < x < arr[b+1] - int i = (a + b) / 2; - if (arr[i] < x) - a = i + 1; - else if (arr[i] > x) - b = i - 1; - else - return i; // because arr[i] == x - } - // Now a > b, in fact a = b+1 and b = a -1, and so arr[b] < x < arr[a] - // TODO: Senthil Kumaran - Why ~a ? - // return ~a; - return -1; - } - - public static void main(String[] args) { - double[] arr = { 4, 5, 6, 7, 8, 10, 12, 14}; - System.out.println(binarySearch(arr, 6.0)); - System.out.println(binarySearch(arr, 9.0)); - } -} diff --git a/languages/java/BitwiseOperators.java b/languages/java/BitwiseOperators.java deleted file mode 100644 index 72749205..00000000 --- a/languages/java/BitwiseOperators.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Example 47 - Bitwise Operators and Shift Operators - */ -public class BitwiseOperators { - - static void println4(int n) { - for (int i = 3; i >=0 ; i--) { - System.out.println(n>>i & 1); - } - System.out.println(); - } - - public static void main(String[] args) throws Exception { - int a = 0x3; - int b = 0x5; - println4(a); - println4(b); - println4(~a); - println4(~b); - println4(a & b); - println4(a ^ b); - println4(a | b); - } -} diff --git a/languages/java/BlockStatements.java b/languages/java/BlockStatements.java deleted file mode 100644 index 88228f23..00000000 --- a/languages/java/BlockStatements.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Example 61 - Block Statements - */ -public class BlockStatements { - - public static void main(String[] args) { - int offset = 10; - - class Pair { - public final int fst, snd; - - Pair(int fst, int snd) { - this.fst = fst; - this.snd = snd; - } - - public String toString() { - return String.format("(%d, %d)", fst, snd); - } - } - - { - Pair p1 = new Pair(10, 10+offset); - System.out.println(p1); - } - - { - Pair p1 = new Pair(200, 300); - System.out.println(p1); - } - - } -} diff --git a/languages/java/BuildingConcordance.java b/languages/java/BuildingConcordance.java deleted file mode 100644 index e8a752fc..00000000 --- a/languages/java/BuildingConcordance.java +++ /dev/null @@ -1,49 +0,0 @@ -import java.io.*; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -/** - * Example 127 Building a Concordance - */ -class BuildingConcordance { - - static SortedMap> buildIndex(String filename) throws IOException { - - Reader r = new BufferedReader(new FileReader(filename)); - StreamTokenizer stok = new StreamTokenizer(r); - stok.quoteChar('"'); - stok.ordinaryChars('!', '/'); - stok.nextToken(); - - SortedMap> index = new TreeMap>(); - - while (stok.ttype != StreamTokenizer.TT_EOF) { - if (stok.ttype == StreamTokenizer.TT_WORD) { - SortedSet ts; - if (index.containsKey(stok.sval)) - ts = index.get(stok.sval); - else { - ts = new TreeSet(); - index.put(stok.sval, ts); - } - ts.add(stok.lineno()); - } - stok.nextToken(); - } - return index; - } - - - public static void main(String[] args) { - try { - SortedMap> concord = buildIndex("WeekdayNametoNumberHashMap.java"); - - for(String word: concord.keySet()) - System.out.println(word + concord.get(word).toString()); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/languages/java/CallingNonOverloaded.java b/languages/java/CallingNonOverloaded.java deleted file mode 100644 index 232f36ab..00000000 --- a/languages/java/CallingNonOverloaded.java +++ /dev/null @@ -1,60 +0,0 @@ -import java.util.ArrayList; - -/** - * Example 56 - Calling Non Overloaded, Non Overridden Methods - */ -class CallingNonOverloaded { - - static class SPoint { - static ArrayList allpoints = new ArrayList(); - int x, y; - - SPoint(int x, int y) { - allpoints.add(this); - this.x = x; - this.y = y; - } - - void move(int dx, int dy) { - x += dx; - y += dy; - } - - public String toString() { - return "(" + x + ", " + y + ")"; - } - - int getIndex() { - return allpoints.indexOf(this); - } - - static int getSize() { - return allpoints.size(); - } - - static SPoint getPoint(int i) { - return allpoints.get(i); - } - - } - - public static void main(String[] args) { - System.out.println("Number of points created: " + SPoint.getSize()); - SPoint p = new SPoint(12, 123); - SPoint q = new SPoint(200, 10); - SPoint r = new SPoint(99, 12); - SPoint s = p; - - // Interesting - q = null; - - System.out.println("Number of points created: " + SPoint.getSize()); - // Bad Style - System.out.println("Number of points created: " + q.getSize()); - System.out.println("r is point number" + r.getIndex()); - for (int i = 0; i < SPoint.getSize(); i++) - System.out.println("SPoint number " + i + " is " + SPoint.getPoint(i)); - } - - -} diff --git a/languages/java/CallingOverloaded.java b/languages/java/CallingOverloaded.java deleted file mode 100644 index 5bc8639e..00000000 --- a/languages/java/CallingOverloaded.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Example 58 - Calling Overloaded Methods - */ -class CallingOverloaded { - static class Access { - private static int x; - static class SI { - private static int y = x; // Access private x from enclosing class - } - - static void m() { - int z = SI.y; // Access private y from nested class - } - - double m(int i) { - return i; - } - boolean m(boolean b) { - return !b; - } - - static double m(int x, int y) { - return x + y + 1; - } - - static double m(double x, double y) { - return x + y + 3; - } - } - - public static void main(String[] args) { - Access a = new Access(); - System.out.println(Access.m(10, 20)); - System.out.println(Access.m(10, 20.0)); - System.out.println(Access.m(10.0, 20)); - System.out.println(Access.m(10.0, 20.0)); - } - -} diff --git a/languages/java/CallingOverriddenConstructor.java b/languages/java/CallingOverriddenConstructor.java deleted file mode 100644 index 522cb9aa..00000000 --- a/languages/java/CallingOverriddenConstructor.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Example 60 - Calling Overridden Methods from a Constructor - */ - -class D1 { - D1() { - m2(); - } - - void m1() { - System.out.println("D1.m1"); - } - - void m2() { - System.out.println("D1.m2"); - m1(); - } -} - -class D2 extends D1 { - int f; - D2() { - f = 7; - } - - void m1() { - System.out.println("D2.m1: " + f); - } -} - -class CallingOverriddenConstructor { - public static void main(String[] args) { - D2 d2 = new D2(); - D1 d1 = new D1(); - d2.m1(); - d2.m2(); - d1.m1(); - d1.m2(); - } - -} diff --git a/languages/java/CallingOverriden.java b/languages/java/CallingOverriden.java deleted file mode 100644 index 247ba183..00000000 --- a/languages/java/CallingOverriden.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Example 59 - Calling Overridden and Overloaded Methods - */ -class C1 { - static void m1(double d) { - System.out.println("11d"); - } - void m1(int i) { - System.out.println("11i"); - } - void m2(int i) { - System.out.println("12i"); - } -} - -class C2 extends C1 { - static void m1(double d) { - System.out.println("21d"); - } - - void m1(int i) { - System.out.println("21i"); - } - - void m2(double d) { - System.out.println("22d"); - } - - void m2(Integer ii) { - System.out.println("22ii"); - } - - void m3(int i) { - System.out.println("23i"); - } - - void m4(Integer ii) { - System.out.println("24ii"); - } - -} -class CallingOverriden { - - public static void main(String[] args) { - int i = 17; - Integer ii = new Integer(i); - double d = 17.0; - C2 c2 = new C2(); - C1 c1 = c2; - c1.m1(i); c2.m1(i); c1.m1(d); c2.m1(d); - c1.m2(i); - c2.m2(i); - c2.m2(ii); - c2.m3(ii); - c2.m4(i); - } - -} diff --git a/languages/java/ClassesInterfaces.java b/languages/java/ClassesInterfaces.java deleted file mode 100644 index bb48df3c..00000000 --- a/languages/java/ClassesInterfaces.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Example 86 - Classes Implementing Interfaces - */ - -import javax.swing.*; -import java.applet.Applet; -import java.awt.*; - -interface Colored { Color getColor();} -interface Drawable { void draw(Graphics g);} -interface ColoredDrawable extends Colored, Drawable {} - -class ColoredPoint extends Point implements Colored { - Color c; - ColoredPoint(int x, int y, Color c) { - super(x, y); - this.c = c; - } - - @Override - public Color getColor() { - return c; - } -} - -class ColoredDrawablePoint extends ColoredPoint implements ColoredDrawable { - - ColoredDrawablePoint(int x, int y, Color c) { - super(x, y, c); - } - - @Override - public void draw(Graphics g) { - g.fillRect(x, y, 1, 1); - } -} - -class ColoredRectangle implements ColoredDrawable { - int x1, x2, y1, y2; - Color c; - - ColoredRectangle(int x1, int y1, int x2, int y2, Color c) { - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - this.c = c; - } - - public Color getColor() { - return c; - } - - public void draw(Graphics g) { - g.drawRect(x1, y1, x2-x1, y2-y1); - } -} - -class ClassesInterfaces extends Applet{ - - public static void main(String[] args) { - JFrame jp1 = new JFrame(); - ColoredRectangle rect = new ColoredRectangle(10, 10, 30, 30, Color.BLACK); - // TODO: Senthil Kumaran - Use Graphics object g. - ClassesInterfaces c = new ClassesInterfaces(); - jp1.getContentPane().add(c, BorderLayout.CENTER); - jp1.setVisible(true); - - } - -} diff --git a/languages/java/Comments.java b/languages/java/Comments.java deleted file mode 100644 index 7d1da2c3..00000000 --- a/languages/java/Comments.java +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Example 1 - Comments - */ -class Comments { - //This is single line comment - - /* - This is a multi-line comment, which can span across lines. - */ - public static void main(String[] arg) { - int /* The delimited comment can extend over a part of the line */ x = 42; - System.out.printf("%d",x); - } -} diff --git a/languages/java/CompleteInputOutput.java b/languages/java/CompleteInputOutput.java deleted file mode 100644 index 40c0ba00..00000000 --- a/languages/java/CompleteInputOutput.java +++ /dev/null @@ -1,21 +0,0 @@ -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -/** - * Example 140 - A Complete Input-Output Example - */ -class CompleteInputOutput { - - public static void main(String[] args) throws IOException { - BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); - int count = 0; - String s = r.readLine(); - while (s != null & !s.equals("")) { - count++; - s = r.readLine(); - } - System.out.println("You entered " + count + " non empty lines"); - } - -} diff --git a/languages/java/CompoundAssignment.java b/languages/java/CompoundAssignment.java deleted file mode 100644 index 771bbc1d..00000000 --- a/languages/java/CompoundAssignment.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Example 50 - Compound Assignment Operators - */ -class CompoundAssignment { - - static double multiply(double[] xs) { - double prod = 1.0; - for (int i = 0; i < xs.length; i++) { - prod *= xs[i]; - } - return prod; - } - - public static void main(String[] args) { - double[] xs = {1.0, 2.0, 3.0}; - System.out.println(multiply(xs)); - } -} diff --git a/languages/java/ConcatCliArgs.java b/languages/java/ConcatCliArgs.java deleted file mode 100644 index e007a361..00000000 --- a/languages/java/ConcatCliArgs.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Example 100 - Efficiently Concatenating All Command Line Arguments - */ -class ConcatCliArgs { - public static void main(String[] args) { - StringBuilder res = new StringBuilder(); - for (int i = 0; i < args.length; i++) - res.append(args[i]); - System.out.println(res.toString()); - } -} diff --git a/languages/java/Concatenate.java b/languages/java/Concatenate.java deleted file mode 100644 index cd6450b2..00000000 --- a/languages/java/Concatenate.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Example 9 Concatenating all Command Line Arguments. - */ - -class Concatenate { - public static void main(String[] args) { - String res = ""; - for(int i = 0; i < args.length; i++) - res += args[i]; - System.out.println(res); - } -} diff --git a/languages/java/ConcordanceUsingIterables.java b/languages/java/ConcordanceUsingIterables.java deleted file mode 100644 index cac96dcc..00000000 --- a/languages/java/ConcordanceUsingIterables.java +++ /dev/null @@ -1,49 +0,0 @@ -import java.io.*; -import java.util.*; - -/** - * Example 130 - Printing a Concordance Using Iterables - */ -class ConcordanceUsingIterables { - - static SortedMap> buildIndex(String filename) throws IOException { - - Reader r = new BufferedReader(new FileReader(filename)); - StreamTokenizer stok = new StreamTokenizer(r); - stok.quoteChar('"'); - stok.ordinaryChars('!', '/'); - stok.nextToken(); - - SortedMap> index = new TreeMap>(); - - while (stok.ttype != StreamTokenizer.TT_EOF) { - if (stok.ttype == StreamTokenizer.TT_WORD) { - SortedSet ts; - if (index.containsKey(stok.sval)) - ts = index.get(stok.sval); - else { - ts = new TreeSet(); - index.put(stok.sval, ts); - } - ts.add(stok.lineno()); - } - stok.nextToken(); - } - return index; - } - - static void printIndex(SortedMap> index) { - for (Map.Entry> entry: index.entrySet()) { - System.out.print(entry.getKey() + ": "); - SortedSet lineNoSet = entry.getValue(); - for (int lineno: lineNoSet) - System.out.print(lineno + " "); - System.out.println(); - } - } - - public static void main(String[] args) throws IOException { - SortedMap> concord = buildIndex("WeekdayNametoNumberHashMap.java"); - printIndex(concord); - } -} diff --git a/languages/java/ConcreteCollection.java b/languages/java/ConcreteCollection.java deleted file mode 100644 index 4d186e4e..00000000 --- a/languages/java/ConcreteCollection.java +++ /dev/null @@ -1,76 +0,0 @@ -import java.util.*; - -/** - * Example 121 - Using the Concrete Collection and Map Classes - */ - -class ConcreteCollection { - public static void main(String[] args) { - List list1 = new LinkedList(); - list1.add("list"); - list1.add("dup"); - list1.add("x"); - list1.add("dup"); - traverse(list1); - - List list2 = new ArrayList(); - list2.add("list"); - list2.add("dup"); - list2.add("x"); - list2.add("dup"); - traverse(list2); - - Set set1 = new HashSet(); - set1.add("set"); - set1.add("dup"); - set1.add("x"); - set1.add("dup"); - traverse(set1); - - SortedSet set2 = new TreeSet(); - set2.add("set"); - set2.add("dup"); - set2.add("x"); - set2.add("dup"); - traverse(set2); - - LinkedHashSet set3 = new LinkedHashSet(); - set3.add("set"); - set3.add("dup"); - set3.add("x"); - set3.add("dup"); - traverse(set3); - - Map m1 = new HashMap(); - m1.put("map", "J"); - m1.put("dup", "K"); - m1.put("x", "M"); - m1.put("dup", "L"); - traverse(m1.keySet()); - traverse(m1.values()); - - SortedMap m2 = new TreeMap(); - m2.put("map", "J"); - m2.put("dup", "K"); - m2.put("x", "M"); - m2.put("dup", "L"); - traverse(m2.keySet()); - traverse(m2.values()); - - LinkedHashMap m3 = new LinkedHashMap(); - m3.put("map", "J"); - m3.put("dup", "K"); - m3.put("x", "M"); - m3.put("dup", "L"); - traverse(m3.keySet()); - traverse(m3.values()); - - } - - static void traverse(Collection coll) { - for(String elem: coll) - System.out.print(elem + " "); - System.out.println(); - - } -} diff --git a/languages/java/ConditionalExpression.java b/languages/java/ConditionalExpression.java deleted file mode 100644 index e97685aa..00000000 --- a/languages/java/ConditionalExpression.java +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Example 51 - Conditional Expression - */ -public class ConditionalExpression { - - static double absolute(double x) { - return (x >= 0 ? x : -x); - } - - public static void main(String[] args) { - Double x = 5.12; - System.out.println(absolute(x)); - } - -} diff --git a/languages/java/ConstraintsType.java b/languages/java/ConstraintsType.java deleted file mode 100644 index 947abd1c..00000000 --- a/languages/java/ConstraintsType.java +++ /dev/null @@ -1,36 +0,0 @@ -import java.util.Date; - -/** - * Example 110 - Constraints Involving Type Parameters - */ - -class ComparablePair, U extends Comparable> - implements Comparable> - { - - public final T fst; - public final U snd; - - public ComparablePair(T fst, U snd) { - this.fst = fst; - this.snd = snd; - } - - @Override - public int compareTo(ComparablePair that) { - int firstCmp = this.fst.compareTo(that.fst); - return firstCmp != 0 ? firstCmp : this.snd.compareTo(that.snd); - } - } -class ConstraintsType { - - public static void main(String[] args) { - Date d = new Date(10); - String s = "Senthil"; - ComparablePair p1 = new ComparablePair(s, d); - ComparablePair p2 = new ComparablePair("Kumaran", new Date(11)); - ComparablePair p3 = new ComparablePair(s, d); - System.out.println(p1.compareTo(p2)); - System.out.println(p1.compareTo(p3)); - } -} diff --git a/languages/java/ConstructorOverloading.java b/languages/java/ConstructorOverloading.java deleted file mode 100644 index 5d768dc5..00000000 --- a/languages/java/ConstructorOverloading.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Example 36 - Constructor Overloading; Calling Another Constructor - */ -class ConstructorOverloading { - int x, y; - - ConstructorOverloading(int x, int y) { - this.x = x; - this.y = y; - } - - ConstructorOverloading(ConstructorOverloading c) { - this(c.x, c.y); - } - - void incr(int x1, int y1) { - x += x1; - y += y1; - } - - public String toString() { - return "(" + x + ", " + y + ")"; - } - - public static void main(String[] args) { - ConstructorOverloading c1 = new ConstructorOverloading(10, 20); - c1.incr(40, 40); - System.out.println(c1); - } -} diff --git a/languages/java/ConversionPrimitive.java b/languages/java/ConversionPrimitive.java deleted file mode 100644 index cd3256d9..00000000 --- a/languages/java/ConversionPrimitive.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Example 4 Conversion between Primitive Types - * - */ -class ConversionPrimitive { - private static void floatdouble(float f, double d) { - System.out.println(f + " " + d); - } - private static void bytecharshort(byte b, char c, short s) { - System.out.println(b + " " + (int) c + " " + s); - } - private static void intint(int i1, int i2) { - System.out.println(i1 + " " + i2); - } - - public static void main(String[] args) { - int i1 = 1000111222, i2 = 40000, i3 = -1; - floatdouble(i1, i1); - bytecharshort((byte)i2, (char)i2, (short)i2); - bytecharshort((byte)i3, (char)i3, (short)i3); - intint((int)1.9, (int)-1.9); - intint((int)1.5, (int)-1.5); - intint((int)2.5, (int)-2.5); - } -} diff --git a/languages/java/CountEs.java b/languages/java/CountEs.java deleted file mode 100644 index cb45c84f..00000000 --- a/languages/java/CountEs.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Example 10 Counting the Number of e's in a String. - */ -class CountEs { - static int ecount(String s) { - int ecount = 0; - for (int i=0; i < s.length(); i++) - if (s.charAt(i) == 'e') - ecount++; - return ecount; - } - - public static void main(String[] args) { - System.out.println(CountEs.ecount("elepantine")); - } -} diff --git a/languages/java/DeclaringCheckedException.java b/languages/java/DeclaringCheckedException.java deleted file mode 100644 index 03323bdf..00000000 --- a/languages/java/DeclaringCheckedException.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Declaring a Checked Exception Class - */ - -class WeekdayException extends Exception { - public WeekdayException(String wday) { - super("Illegal weekday: " + wday); - } -} - -public class DeclaringCheckedException { - - static final String[] wdays = - {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; - - - static int wdayno4(String wday) throws WeekdayException { - for (int i = 0; i < wdays.length; i++) - if (wday.equals(wdays[i])) - return i + 1; - throw new WeekdayException(wday); - } - - public static void main(String[] args) throws WeekdayException { - System.out.println(wdayno4("Monday")); - System.out.println(wdayno4("Sommar")); - } -} diff --git a/languages/java/Describe.java b/languages/java/Describe.java deleted file mode 100644 index 0395b7e3..00000000 --- a/languages/java/Describe.java +++ /dev/null @@ -1,28 +0,0 @@ -public class Describe { - static void describe(Class clazz, String pad, String leadin) { - if (clazz == null) return; - String type = - clazz.isInterface() ? "interface" : - clazz.isArray() ? "array" : - clazz.isPrimitive() ? "primitive" : - clazz.isEnum() ? "enum" : - "class"; - System.out.printf("%s%s%s %s ( %s )%n", - pad, leadin, type, clazz.getSimpleName(), clazz.getName()); - for (Class interfaze : clazz.getInterfaces()) { - describe(interfaze, pad + " ", "implements "); - } - describe(clazz.getComponentType(), pad + " ", "elements are "); - describe(clazz.getSuperclass(), pad + " ", "extends "); -} -static void describe(Class clazz) { - describe(clazz, "", ""); - System.out.println(); -} -public static void main(String[] args) { - describe(boolean[][].class); - describe(java.math.RoundingMode.class); - describe(java.util.ArrayList.class); - describe(void.class); -} -} diff --git a/languages/java/DoWhileRollaDie.java b/languages/java/DoWhileRollaDie.java deleted file mode 100644 index b1066a60..00000000 --- a/languages/java/DoWhileRollaDie.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Example 75 - Using do-while to Roll a Die and Compute Sum Until 5 or 6 Comes up - */ -class DoWhileRollaDie { - - public static void main(String[] args) { - int sum = 0, eyes; - - do { - eyes = (int) (1 + 6 * Math.random()); - sum += eyes; - } while (eyes < 5); - - sum -= eyes; // remove the 5 added. - - System.out.println(sum); - } -} diff --git a/languages/java/EmptyStatement.java b/languages/java/EmptyStatement.java deleted file mode 100644 index 59579e82..00000000 --- a/languages/java/EmptyStatement.java +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Example 62 - Empty Statement and Infinite Loop Because of misplaced semicolon - */ -public class EmptyStatement { - - public static void main(String[] args) { - - int i = 0; - // misplaced semicolon; runs forver and ever. - while(i < 10); - i++; - } -} diff --git a/languages/java/EnhancedForStatement.java b/languages/java/EnhancedForStatement.java deleted file mode 100644 index 6fdb37ae..00000000 --- a/languages/java/EnhancedForStatement.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Example 69 - Enhanced for statement on an Array - */ -public class EnhancedForStatement { - public static void main(String[] args) { - int[] arr = { 2, 3, 4, 5, 7, 11}; - int sum = 0; - for(int i: arr) - sum += i; - System.out.println(sum); - } -} diff --git a/languages/java/EqualityStrings.java b/languages/java/EqualityStrings.java deleted file mode 100644 index ed4a5831..00000000 --- a/languages/java/EqualityStrings.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Example 7 Equality of Strings and the Subtlety of (+) Operator. - */ -class EqualityStrings { - public static void main(String[] args) { - String s1 = "abc"; - String s2 = s1 + ""; - String s3 = s1; - String s4 = s1.toString(); - - System.out.println("s1 and s2 identical objects: " + (s1 == s2)); - System.out.println("s1 and s3 identical objects: " + (s1 == s3)); - System.out.println("s1 and s4 identical objects: " + (s1 == s4)); - System.out.println("s1 and s2 contain same text: " + (s1.equals(s2))); - System.out.println("s1 and s3 contain same text: " + (s1.equals(s3))); - - System.out.println(10 + 25 + "A"); - System.out.println("A" + 10 + 25); - } -} diff --git a/languages/java/EqualsMethod.java b/languages/java/EqualsMethod.java deleted file mode 100644 index 42859e37..00000000 --- a/languages/java/EqualsMethod.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Example 134 - An equals Method for the Time Class - */ -public class EqualsMethod { - - static class Time implements Comparable
  • \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 5ce4944f..00000000 --- a/languages/python/software_engineering_exceptions_testing.py +++ /dev/null @@ -1,12 +0,0 @@ -from urllib2 import URLError, HTTPError -from StringIO 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 5de3eb06..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 d5f8059a..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(raw_input()) -for i in range(t): - n = int(raw_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 e989ba37..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 HTMLParser 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 735c319b..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.iteritems()) - 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 cd4688df..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 b93fffb9..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 8fbd36b5..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 = 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 45591e49..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 24e73b3e..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 fd603e66..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 91cb2015..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 05753219..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 e257405d..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 26309e57..00000000 --- a/languages/python/software_engineering_simple_threading1.py +++ /dev/null @@ -1,15 +0,0 @@ -import threading -import urllib - -class MultiUrl(threading.Thread): - def __init__(self, url): - threading.Thread.__init__(self) - self.url = url - def run(self): - urllib.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 d5d4677e..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 6421404a..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 c525013f..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 09d3ef5d..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 0a1d02c3..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 cddc1693..00000000 --- a/languages/python/software_engineering_test_codec01.py +++ /dev/null @@ -1,20 +0,0 @@ -if __name__ == '__main__': - # define our Unicode string - uni = u"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 = unicode(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 30279183..00000000 --- a/languages/python/software_engineering_test_codec02.py +++ /dev/null @@ -1,7 +0,0 @@ -a = u'\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 f9994646..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 = unicode(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 8f962e77..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 e2cb744c..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 a877d209..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 0d28870e..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 13dd2033..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 urllib2 -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 be1a4284..00000000 --- a/languages/python/software_engineering_xmlrpcclient.py +++ /dev/null @@ -1,21 +0,0 @@ -import xmlrpclib -proxy = xmlrpclib.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 716312cb..00000000 --- a/languages/python/software_engineering_xmlrpcserver.py +++ /dev/null @@ -1,41 +0,0 @@ -from SimpleXMLRPCServer 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/web_cgi_ex.py b/languages/python/web_cgi_ex.py deleted file mode 100755 index 9733ac4c..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_codepad_post.py b/languages/python/web_codepad_post.py deleted file mode 100644 index 2fc32156..00000000 --- a/languages/python/web_codepad_post.py +++ /dev/null @@ -1,18 +0,0 @@ -import urllib2 -import urllib - -url = 'http://codepad.org' - -with open('locate.py') as f: - code = f.read() - -parameters = {'project':'uthcode', - 'lang':'Python', - 'code': code, - 'private':'', - 'run':'False', - 'submit':'Submit'} - -seq = urllib.urlencode(parameters) -r = urllib2.urlopen(url,seq) -print r.url + '/fork' diff --git a/languages/python/web_cookielib_example.py b/languages/python/web_cookielib_example.py deleted file mode 100644 index 30a4c955..00000000 --- a/languages/python/web_cookielib_example.py +++ /dev/null @@ -1,16 +0,0 @@ -import cookielib, urllib2 - -cj = cookielib.CookieJar() -opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) - -req = urllib2.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 = urllib2.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 75244867..00000000 --- a/languages/python/web_crawl.py +++ /dev/null @@ -1,123 +0,0 @@ -import urllib2 -import urllib -import urlparse -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 = urlparse.urlparse(URL) # for default -global_url = [] -visited_url = [] - -def getimages(page): - images = [] - try: - soup = BeautifulSoup(urllib2.urlopen(page)) - for image in soup.findAll("img"): - img = image["src"] - if img.split('.')[-1] in ('jpg','png','jpeg','gif'): - parsed_img = urlparse.urlparse(img) - if not parsed_img.scheme: - img = urlparse.urljoin(URL,parsed_img.path) - images.append(img) - except (IOError, KeyError, IndexError): - pass - return images - -def guess_product_page(page): - try: - soup = BeautifulSoup(urllib2.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(urllib2.urlopen(node)) - for l in soup.findAll("a"): - l = l["href"] - parsed = urlparse.urlparse(l) - if (parsed.scheme and (parsed.scheme in ('http','https')) and (parsed.netloc in parsed_url.netloc)): - link = urlparse.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 = urlparse.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, - 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.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 b04ae761..00000000 --- a/languages/python/web_crawl2.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf8 -*- -import cStringIO 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 = unicode(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 7e4a55e4..00000000 --- a/languages/python/web_http_auth_header_code.py +++ /dev/null @@ -1,19 +0,0 @@ -import urllib2 - -if __name__ == '__main__': - theurl = "http://mail.google.com/mail/#inbox" - req = urllib2.Request(theurl) - try: - handle = urllib2.urlopen(req) - print 'here' - except IOError, 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 16036eea..00000000 --- a/languages/python/web_httplib_example_1.py +++ /dev/null @@ -1,42 +0,0 @@ -import httplib - -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 = httplib.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 a56be186..00000000 --- a/languages/python/web_httplib_example_2.py +++ /dev/null @@ -1,9 +0,0 @@ -import httplib -import pudb -pudb.set_trace() -conn = httplib.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 28d8cdc9..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 d0f64059..00000000 --- a/languages/python/web_httplib_head.py +++ /dev/null @@ -1,6 +0,0 @@ -import httplib -conn = httplib.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 12450639..00000000 --- a/languages/python/web_scan_web.py +++ /dev/null @@ -1,13 +0,0 @@ -import re -import urllib - -regex = re.compile(r'href="([^"]+)"') - -def matcher(url, max=10): - """Print the first several URL references in the given URL""" - data = urllib.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 b7071bcc..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 = raw_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 91d0a505..00000000 --- a/languages/python/web_simple_http_processor.py +++ /dev/null @@ -1,56 +0,0 @@ -import sys -import urllib2 -import cookielib - -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 = cookielib.LWPCookieJar() -opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cjar),HTTPMyDebugProcessor(),) -#opener = urllib2.build_opener(HTTPMyDebugProcessor(),) -urllib2.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 = urllib2.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 = urllib2.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 38fc323d..00000000 --- a/languages/python/web_urllib1.py +++ /dev/null @@ -1,2 +0,0 @@ -import urllib -urllib.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 fd55f925..00000000 --- a/languages/python/web_urllib2_1.py +++ /dev/null @@ -1,4 +0,0 @@ -import urllib2 -o = urllib2.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 36d571a1..00000000 --- a/languages/python/web_urllib2_add_data.py +++ /dev/null @@ -1,14 +0,0 @@ -import urllib2 - -URL = 'http://localhost/allowed.html' - -ah = urllib2.HTTPDigestAuthHandler() -ah.add_password('Realm','http://localhost/','senthil','kumaran') -urllib2.install_opener(urllib2.build_opener(ah)) -r = urllib2.Request(URL) -r.add_data("1") -obj = urllib2.urlopen(r) -print obj.read() -r.add_data("10") -obj = urllib2.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 567ece08..00000000 --- a/languages/python/web_urllib2_auth_ex1.py +++ /dev/null @@ -1,6 +0,0 @@ -import urllib2 -authinfo = urllib2.HTTPBasicAuthHandler() -opener = urllib2.build_opener(authinfo) -urllib2.install_opener(opener) -f = urllib2.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 8dc7ea65..00000000 --- a/languages/python/web_urllib2_basic1.py +++ /dev/null @@ -1,11 +0,0 @@ -import urllib2 - -URL = 'http://localhost/basic.html' -passwd = '550charpass50charpass50charpass50charpass50charpass0charpass' -#passwd = 'senthil' -ah = urllib2.HTTPBasicAuthHandler() -ah.add_password('Realm','http://localhost/basic.html','senthil',passwd) -urllib2.install_opener(urllib2.build_opener(ah)) -r = urllib2.Request(URL) -obj = urllib2.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 8a42e8c4..00000000 --- a/languages/python/web_urllib2_basic2.py +++ /dev/null @@ -1,79 +0,0 @@ -import urllib2 - -URL = 'http://localhost/basic.html' - -ah = urllib2.HTTPBasicAuthHandler() -ah.add_password('Realm','http://localhost/','username','veryverylongpassword') -urllib2.install_opener(urllib2.build_opener(ah)) -r = urllib2.Request(URL) -obj = urllib2.urlopen(r) -print obj.read() - -print '*********************************************************' -import urllib2 -import sys -import re -import base64 -from urlparse 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 = urllib2.Request(theurl) -try: - handle = urllib2.urlopen(req) -except IOError, 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 = urllib2.urlopen(req) -except IOError, 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 5fd299ae..00000000 --- a/languages/python/web_urllib2_basic3.py +++ /dev/null @@ -1,14 +0,0 @@ -import urllib2 -import base64 - -URL = 'http://localhost/basic.html' -passwd = '550charpass50charpass50charpass50charpass50charpass0charpass' -#passwd = 'senthil' -request = urllib2.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 = urllib2.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 58a03442..00000000 --- a/languages/python/web_urllib2_basic_digest1.py +++ /dev/null @@ -1,16 +0,0 @@ -import urllib2 - -basic_handler = urllib2.HTTPBasicAuthHandler() -basic_handler.add_password('Realm','http://localhost/','senthil','senthil') - -digest_handler = urllib2.HTTPDigestAuthHandler() -digest_handler.add_password('Realm','http://localhost/','senthil','kumaran') -opener = urllib2.build_opener(basic_handler, digest_handler) -opener = urllib2.build_opener(digest_handler, basic_handler) -urllib2.install_opener(opener) - -basic_url = r'http://localhost/basic.html' -digest_url = r'http://localhost/allowed.html' - -print urllib2.urlopen(digest_url).read() -print urllib2.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 83e6650a..00000000 --- a/languages/python/web_urllib2_binary_upload.py +++ /dev/null @@ -1,93 +0,0 @@ -import itertools -import mimetools -import mimetypes -from cStringIO import StringIO -import urllib -import urllib2 - -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 = urllib2.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 urllib2.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 3ee77f9d..00000000 --- a/languages/python/web_urllib2_debug_headers.py +++ /dev/null @@ -1,28 +0,0 @@ -import cookielib -import urllib2 - -cookiejar = cookielib.LWPCookieJar() -http_handler = urllib2.HTTPHandler(debuglevel=1) -opener = urllib2.build_opener(http_handler,urllib2.HTTPCookieProcessor(cookiejar)) -urllib2.install_opener(opener) -#url = 'https://www.orange.sk/' -url = 'https://www.idcourts.us/repository/start.do' -req = urllib2.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 9248a1d4..00000000 --- a/languages/python/web_urllib2_digest.py +++ /dev/null @@ -1,10 +0,0 @@ -import urllib2 - -URL = 'http://localhost/allowed.html' - -ah = urllib2.HTTPDigestAuthHandler() -ah.add_password('Realm','http://localhost/','senthil','kumaran') -urllib2.install_opener(urllib2.build_opener(ah)) -r = urllib2.Request(URL) -obj = urllib2.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 8f3cb88d..00000000 --- a/languages/python/web_urllib2_digest2.py +++ /dev/null @@ -1,12 +0,0 @@ -import urllib2 -import getpass - -URL = 'http://livejournal.com/users/phoe6/data/rss?auth=digest' - -ah = urllib2.HTTPDigestAuthHandler() -password = getpass.getpass() -ah.add_password('lj','http://phoe6.livejournal.com/','phoe6',password) -urllib2.install_opener(urllib2.build_opener(ah)) -r = urllib2.Request(URL) -obj = urllib2.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 23c2babd..00000000 --- a/languages/python/web_urllib2_headers_ex1.py +++ /dev/null @@ -1,16 +0,0 @@ -import urllib2 -import urllib - -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.urlencode(values) -req = urllib2.Request(url, data, headers) -response = urllib2.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 4402e033..00000000 --- a/languages/python/web_urllib2_proxy_auth.py +++ /dev/null @@ -1,11 +0,0 @@ -import urllib2 - -proxy = urllib2.ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport', - 'https': 'https://username:password@proxyurl:proxyport'} - ) -auth = urllib2.HTTPBasicAuthHandler() -opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) -urllib2.install_opener(opener) - -conn = urllib2.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 6cc331e1..00000000 --- a/languages/python/web_urllib2_test.py +++ /dev/null @@ -1,25 +0,0 @@ -import urllib2 - - -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 = urllib2.HTTPDigestAuthHandler(FixedPasswordMgr('phoe6', 'xxxxx')) - -opener = urllib2.build_opener(authhandler) -urllib2.install_opener(opener) - -for user in ['shortcipher', 'numberland', 'adrian2084', 'rocketjon', 'si1entdave', 'nightshade37']: - url = 'http://' + user + '.livejournal.com/data/atom?auth=digest' - pagehandle = urllib2.urlopen(url) - print 'ok ' + user diff --git a/languages/ruby/being_rescue_else_ensure.rb b/languages/ruby/being_rescue_else_ensure.rb deleted file mode 100644 index 53eaee1f..00000000 --- a/languages/ruby/being_rescue_else_ensure.rb +++ /dev/null @@ -1,11 +0,0 @@ -begin - puts "Hello, world!" - 1/0 -rescue => e - puts e - puts "rescue" -else - puts "else" -ensure - puts "ensure" -end diff --git a/languages/ruby/check_nil.rb b/languages/ruby/check_nil.rb deleted file mode 100644 index ea3653d3..00000000 --- a/languages/ruby/check_nil.rb +++ /dev/null @@ -1,6 +0,0 @@ -if true.nil? - print "true" -else - print "false" -end - diff --git a/languages/ruby/class_and_object.rb b/languages/ruby/class_and_object.rb deleted file mode 100644 index 079bb4bf..00000000 --- a/languages/ruby/class_and_object.rb +++ /dev/null @@ -1,22 +0,0 @@ -class Rectangle - def initialize(length, breadth) - @length = length - @breadth = breadth - end - - def perimeter - 2 * (@length + @breadth) - end - - def area - @length * @breadth - end -end - -rect = Rectangle.new(10, - 20) - -# In ruby, you initialize an object using the new method -# -puts rect.perimeter -puts rect.area diff --git a/languages/ruby/conditionals.rb b/languages/ruby/conditionals.rb deleted file mode 100644 index 336f8dec..00000000 --- a/languages/ruby/conditionals.rb +++ /dev/null @@ -1,4 +0,0 @@ -closeit = false -puts "close it" if closeit -closeit = true -puts "does not closes it" if closedit diff --git a/languages/ruby/constant_assignment.rb b/languages/ruby/constant_assignment.rb deleted file mode 100644 index 1a69d354..00000000 --- a/languages/ruby/constant_assignment.rb +++ /dev/null @@ -1,2 +0,0 @@ -MY_CONST = 1 -MY_CONST = 2 # generates a warning diff --git a/languages/ruby/forloop.rb b/languages/ruby/forloop.rb deleted file mode 100644 index 33358695..00000000 --- a/languages/ruby/forloop.rb +++ /dev/null @@ -1,4 +0,0 @@ -array = [1, 2, 3, 4, 5] -for i in array - puts i -end diff --git a/languages/ruby/handle_exceptions.rb b/languages/ruby/handle_exceptions.rb deleted file mode 100644 index 9899fed8..00000000 --- a/languages/ruby/handle_exceptions.rb +++ /dev/null @@ -1,16 +0,0 @@ -class NewTypeError < ArgumentError -end - -def inverse(x) - begin - raise NewTypeError, 'Argument is not numeric' unless x.is_a? Numeric - rescue SecurityError =>e - puts "it is a security error" - rescue ArgumentError => e - puts e.message - puts e.backtrace.inspect - end -end - -inverse(2) -inverse('not a number') diff --git a/languages/ruby/if_statement.rb b/languages/ruby/if_statement.rb deleted file mode 100644 index 60a657b7..00000000 --- a/languages/ruby/if_statement.rb +++ /dev/null @@ -1,5 +0,0 @@ -something = true - -if something == true - puts "something" -end diff --git a/languages/ruby/include_modules.rb b/languages/ruby/include_modules.rb deleted file mode 100644 index 55c0cfa8..00000000 --- a/languages/ruby/include_modules.rb +++ /dev/null @@ -1,2 +0,0 @@ -require "ruby15.rb" -RubyModule::rubyfunction(10) diff --git a/languages/ruby/introspect.rb b/languages/ruby/introspect.rb deleted file mode 100644 index 32d530cc..00000000 --- a/languages/ruby/introspect.rb +++ /dev/null @@ -1,20 +0,0 @@ -module Debug - def whoAmI? - "#{self.type.name} (\##{self.id}): #{self.to_s}" - end -end -class Phonograph - include Debug - # ... -end -class EightTrack - include Debug - # ... -end - -# Gives ArgumentError - Has something happened in the Ruby version? - -ph = Phonograph.new("West End Blues") -et = EightTrack.new("Surrealistic Pillow") -p ph.whoAmI? -p et.whoAmI? diff --git a/languages/ruby/iterate_each.rb b/languages/ruby/iterate_each.rb deleted file mode 100644 index 89bd7b8a..00000000 --- a/languages/ruby/iterate_each.rb +++ /dev/null @@ -1,4 +0,0 @@ -array = [1, 2, 3, 4, 5, 6] -array.each do |i| - puts i -end diff --git a/languages/ruby/kernel_method.rb b/languages/ruby/kernel_method.rb deleted file mode 100644 index 74b7d9fb..00000000 --- a/languages/ruby/kernel_method.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Kernel - def canonical - puts "hello, world" - end -end diff --git a/languages/ruby/module_mixin.rb b/languages/ruby/module_mixin.rb deleted file mode 100644 index 45807930..00000000 --- a/languages/ruby/module_mixin.rb +++ /dev/null @@ -1,18 +0,0 @@ -# Ruby module Mixin example. - -module Debug - def whoAmI? - "#{self.type.name} (\##{self.id}): " - end -end -class Phonograph - include Debug -end -class EightTrack - include Debug - -end -ph = Phonograph.new -et = EightTrack.new -ph.whoAmI? # "Phonograph (#537766170): West End Blues" -et.whoAmI? # "EightTrack (#537765860): Surrealistic Pillow" diff --git a/languages/ruby/modules_with_methods.rb b/languages/ruby/modules_with_methods.rb deleted file mode 100644 index 47ef3a9c..00000000 --- a/languages/ruby/modules_with_methods.rb +++ /dev/null @@ -1,45 +0,0 @@ -module Debug - def whoAmI? - "#{self.type.name} (\##{self.id}): #{self.to_s}" - end -end -class Phonograph - include Debug - - def initialize(title) - @title = title - end - def type - self.class - end - def id - self.object_id - end - def to_s - @title - end -end -class EightTrack - include Debug - - def initialize(title) - @title = title - end - - def type - self.class - end - - def id - self.object_id - end - - def to_s - @title - end -end - -ph = Phonograph.new("West End Blues") -et = EightTrack.new("Surrealistic Pillow") -p ph.whoAmI? -p et.whoAmI? diff --git a/languages/ruby/open_url.rb b/languages/ruby/open_url.rb deleted file mode 100644 index 406c4661..00000000 --- a/languages/ruby/open_url.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "open-uri" - -open("http://www.uthcode.com") do |lost| - puts lost.read -end diff --git a/languages/ruby/puts_examples.rb b/languages/ruby/puts_examples.rb deleted file mode 100644 index 1fd549f7..00000000 --- a/languages/ruby/puts_examples.rb +++ /dev/null @@ -1,7 +0,0 @@ -puts "Hello World!" -puts "Hello Again" -puts "I like typing this." -puts "This is fun." -puts 'Yay! Printing.' -puts "I'd much rather you 'not'." -puts 'I "said" do not touch this.' diff --git a/languages/ruby/puts_functionname.rb b/languages/ruby/puts_functionname.rb deleted file mode 100644 index e0cdc749..00000000 --- a/languages/ruby/puts_functionname.rb +++ /dev/null @@ -1,6 +0,0 @@ -def somefunction - x = "something" - y = x -end -x = somefunction -p x diff --git a/languages/ruby/require_stmt.rb b/languages/ruby/require_stmt.rb deleted file mode 100644 index f4ee057d..00000000 --- a/languages/ruby/require_stmt.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'rubygems' -gem 'RedCloth' diff --git a/languages/ruby/ruby13.rb b/languages/ruby/ruby13.rb deleted file mode 100644 index e0b26a5b..00000000 --- a/languages/ruby/ruby13.rb +++ /dev/null @@ -1,2 +0,0 @@ -p $: -p File.expand_path("../", __FILE__) diff --git a/languages/ruby/ruby16.rb b/languages/ruby/ruby16.rb deleted file mode 100644 index 55c0cfa8..00000000 --- a/languages/ruby/ruby16.rb +++ /dev/null @@ -1,2 +0,0 @@ -require "ruby15.rb" -RubyModule::rubyfunction(10) diff --git a/languages/ruby/ruby5.rb b/languages/ruby/ruby5.rb deleted file mode 100644 index b3ae9ca7..00000000 --- a/languages/ruby/ruby5.rb +++ /dev/null @@ -1,7 +0,0 @@ -#!/opt/twitter/rvm/rubies/ruby-1.9.3-p194/bin/ruby - -puts :'I love Ruby!' -puts :'I love Ruby!.'.to_i - -# ruby5.rb:4:in `
    ': undefined method `to_i' for :"I love Ruby!.":Symbol (NoMethodError) -# diff --git a/languages/ruby/ruby7.rb b/languages/ruby/ruby7.rb deleted file mode 100644 index 79cd91b8..00000000 --- a/languages/ruby/ruby7.rb +++ /dev/null @@ -1,6 +0,0 @@ -at_hotel = true -email = if at_hotel do - address = "something" - address << "new address" - address << "updated address" - end diff --git a/languages/ruby/ruby_function.rb b/languages/ruby/ruby_function.rb deleted file mode 100644 index da64fde6..00000000 --- a/languages/ruby/ruby_function.rb +++ /dev/null @@ -1,7 +0,0 @@ -module RubyModule - def rubyfunction(num) - puts "within rubyfunction" - puts num - end - module_function :rubyfunction -end diff --git a/languages/ruby/see_backtrace.rb b/languages/ruby/see_backtrace.rb deleted file mode 100644 index a066642c..00000000 --- a/languages/ruby/see_backtrace.rb +++ /dev/null @@ -1,13 +0,0 @@ -def a - raise "boom" -end - -def b - a() -end - -begin - b() -rescue => detail - print detail.backtrace.join("\n") -end diff --git a/languages/ruby/simpleNumber.rb b/languages/ruby/simpleNumber.rb deleted file mode 100644 index 6e17c549..00000000 --- a/languages/ruby/simpleNumber.rb +++ /dev/null @@ -1,14 +0,0 @@ -class SimpleNumber - def initialize(num) - raise unless num.is_a?(Numeric) - @x = num - end - - def add(y) - @x + y - end - - def multiply(y) - @x * y - end -end diff --git a/languages/ruby/string_methods.rb b/languages/ruby/string_methods.rb deleted file mode 100644 index 8cb1317f..00000000 --- a/languages/ruby/string_methods.rb +++ /dev/null @@ -1,4 +0,0 @@ -puts :senthil -puts :senthil.to_s -puts :senthil.class -puts :senthil.to_i diff --git a/languages/ruby/string_templates.rb b/languages/ruby/string_templates.rb deleted file mode 100644 index 4bc37df6..00000000 --- a/languages/ruby/string_templates.rb +++ /dev/null @@ -1,3 +0,0 @@ -name = "senthil" -age = 31 -puts "Hello, my name is #{name} and I am #{age} years old!" diff --git a/languages/ruby/string_times.rb b/languages/ruby/string_times.rb deleted file mode 100644 index be93cb88..00000000 --- a/languages/ruby/string_times.rb +++ /dev/null @@ -1 +0,0 @@ -5.times do print "something" end diff --git a/languages/ruby/tc_simpleNumber.rb b/languages/ruby/tc_simpleNumber.rb deleted file mode 100644 index ad5b0004..00000000 --- a/languages/ruby/tc_simpleNumber.rb +++ /dev/null @@ -1,9 +0,0 @@ -require "simpleNumber" -require "test/unit" - -class TestSimpleNumber < Test::Unit::TestCase - def test_simple - assert_equal(4, SimpleNumber.new(2).add(2)) - assert_equal(6, SimpleNumber.new(2).multiply(3)) - end -end diff --git a/learntosolveit.yaml b/learntosolveit.yaml new file mode 100644 index 00000000..77f186c1 --- /dev/null +++ b/learntosolveit.yaml @@ -0,0 +1,61 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: learntosolveit +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: learntosolveit + name: deployment-learntosolveit +spec: + selector: + matchLabels: + app.kubernetes.io/name: app-learntosolveit + replicas: 5 + template: + metadata: + labels: + app.kubernetes.io/name: app-learntosolveit + spec: + containers: + - image: skumaran/learntosolveit:latest + imagePullPolicy: Always + name: app-learntosolveit + ports: + - containerPort: 80 +--- +apiVersion: v1 +kind: Service +metadata: + namespace: learntosolveit + name: service-learntosolveit +spec: + ports: + - port: 80 + targetPort: 80 + protocol: TCP + type: NodePort + selector: + app.kubernetes.io/name: app-learntosolveit +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + namespace: learntosolveit + name: ingress-learntosolveit + annotations: + alb.ingress.kubernetes.io/scheme: internet-facing + alb.ingress.kubernetes.io/target-type: ip +spec: + ingressClassName: alb + rules: + - http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: service-learntosolveit + port: + number: 80 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..af80e1a8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +sphinx +sphinx-wagtail-theme +sphinx-autobuild +breathe 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/css/custom.css b/source/_static/css/custom.css new file mode 100644 index 00000000..a2a804d8 --- /dev/null +++ b/source/_static/css/custom.css @@ -0,0 +1,4 @@ +.bd-content { + flex-grow: 3; + max-width: 100%; +} 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 82a3aa35..774730ce 100644 --- a/source/_templates/layout.html +++ b/source/_templates/layout.html @@ -1,15 +1,19 @@ {% extends "!layout.html" %} +{% block extrahead %} + +{% endblock %} + {% block content %} + {{ super() }} + {% endblock %} {%- block footer %} {{ super() }} {%- endblock %} diff --git a/source/_templates/logo.html b/source/_templates/logo.html index a4a452e6..a40ffdcd 100644 --- a/source/_templates/logo.html +++ b/source/_templates/logo.html @@ -1,4 +1,9 @@ -
    - -
    -
    + + diff --git a/source/conf.py b/source/conf.py index ed8a40b2..a7f2d269 100644 --- a/source/conf.py +++ b/source/conf.py @@ -11,41 +11,7 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys, os -# At the top. -import sphinx_bootstrap_theme - -# ... - -# Activate the theme. -html_theme = 'bootstrap' -html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() - -html_theme_options = { - 'navbar_sidebarrel' : False, - 'navbar_pagenav': False, - 'bootswatch_theme': "united", - 'navbar_site_name': "Navigator", - 'navbar_links': [ - ("Online Tutor", "https://goo.gl/forms/I3NahMbRcAct2TRy2", True), - ], -} - -# 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'] +from datetime import date # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -54,167 +20,49 @@ source_suffix = '.rst' # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' -# The master toctree document. master_doc = 'index' # General information about the project. project = u'Learn To Solve It' -copyright = u'2020, Senthil Kumaran' +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 = '' +version = '2022-01-06' # The full version, including alpha/beta/rc tags. -release = '0.2' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None +release = '' -# 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 "), - 'ruby-suggest-improve': - ("https://github.com/uthcode/learntosolveit/edit/master/languages/ruby/%s", - "Suggest a Code Improvement:"), - 'ruby-better-explain': - ("https://github.com/uthcode/learntosolveit/edit/master/source/ruby/%s", - "Suggest a better explanation for "), - 'java-suggest-improve': - ("https://github.com/uthcode/learntosolveit/edit/master/languages/java/%s", - "Suggest a Code Improvement:"), - 'java-better-explain': - ("https://github.com/uthcode/learntosolveit/edit/master/source/java/%s", - "Suggest a better explanation for "), - 'scala-suggest-improve': - ("https://github.com/uthcode/learntosolveit/edit/master/languages/scala/%s", - "Suggest a Code Improvement:"), - 'scala-better-explain': - ("https://github.com/uthcode/learntsolveit/edit/master/source/scala/%s", - "Suggest a better explanation for "), - 'go-suggest-improve': - ("https://github.com/uthcode/learntosolveit/edit/master/languages/go/%s", - "Suggest a Code Improvement:"), - 'go-better-explain': - ("https://github.com/uthcode/learntosolveit/edit/master/source/go/%s", - "Suggest a better explanation for "), - 'use-local-compiler': - ('http://www.seas.upenn.edu/cets/answers/%s.html', - 'Please use a local c compiler to run this program.'), -} - - - - -# -- 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' +html_static_path = ['_static'] -# 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 +html_extra_path = ["Ads.txt"] -# 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'] +# These paths are either relative to html_static_path +# or fully qualified paths (eg. https://...) + +html_css_files = [ + 'css/custom.css', +] # 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','localtoc.html']} - - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} +html_sidebars = {'**': ['logo.html', 'globaltoc.html']} # If false, no module index is generated. html_use_modindex = False @@ -222,14 +70,35 @@ # 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 a66ddbf1..00000000 --- a/source/cprogramming/Ex_1.10_TbsBlnkSpaces.rst +++ /dev/null @@ -1,37 +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 - -:use-local-compiler:`gcc` - -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 47ffd711..00000000 --- a/source/cprogramming/Ex_1.12_word_per_line.rst +++ /dev/null @@ -1,37 +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 - - -.. runcode:: ../../languages/cprogs/Ex_1.12_word_per_line.c - :language: c - :codesite: ideone - - - -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 b407cca3..00000000 --- a/source/cprogramming/Ex_1.1_exp_helloworld.rst +++ /dev/null @@ -1,59 +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 656463fc..00000000 --- a/source/cprogramming/Ex_1.20_detab.rst +++ /dev/null @@ -1,83 +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 - - -:use-local-compiler:`gcc` - -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 79ca3b33..00000000 --- a/source/cprogramming/Ex_1.21_entab.rst +++ /dev/null @@ -1,56 +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 - -:use-local-compiler:`gcc` - -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 73907a44..00000000 --- a/source/cprogramming/Ex_1.2_exp_printf_c.rst +++ /dev/null @@ -1,61 +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 - - -.. runcode:: ../../languages/cprogs/Ex_1.2_exp_printf_c.c - :language: c - :codesite: ideone - - - -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 eb51efa6..00000000 --- a/source/cprogramming/Ex_3.6_itoa-3.rst +++ /dev/null @@ -1,38 +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. - - - -.. 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 01e0df4a..00000000 --- a/source/cprogramming/Ex_5.15_sortfnr.rst +++ /dev/null @@ -1,31 +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 - - -:use-local-compiler:`gcc` - -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 27967932..00000000 --- a/source/cprogramming/Ex_8.1_mycat.rst +++ /dev/null @@ -1,28 +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 - - -:use-local-compiler:`gcc` - -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 978a61f1..00000000 --- a/source/cprogramming/atoiv2.rst +++ /dev/null @@ -1,16 +0,0 @@ -====== -atoiv2 -====== - -*atoiv2.c* - -.. literalinclude:: ../../languages/cprogs/atoiv2.c - :language: c - :tab-width: 4 - - - -.. 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 new file mode 100644 index 00000000..f2562e6f --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.10_tbsblnkspaces.c @@ -0,0 +1,32 @@ +/** + * 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 + +int main(void) { + int c; + + while ((c = getchar()) != EOF) { + if (c == '\t') { + putchar('\\'); + putchar('t'); + } + + if (c == '\b') { + putchar('\\'); + putchar('b'); + } + + if (c == '\\') { + putchar('\\'); + putchar('\\'); + } + + if (c != '\t' && c != '\b' && c != '\\') + putchar(c); + } + return 0; +} 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 new file mode 100644 index 00000000..c06cd68f --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.13.2_his_vertical.c @@ -0,0 +1,44 @@ +/** + * + * Vertical Histogram of words in a Sentence + * + **/ + +#include + +#define MAXWL 20 /* Maximum length of a word */ +#define MAXNO 25 /* Maximum No of words in a sentence */ + +int main(void) { + int word[MAXNO]; + int i, c, j, nc, nw; + + for (i = 0; i < MAXNO; ++i) + word[i] = 0; + + nc = nw = 0; + + while ((c = getchar()) != EOF) { + ++nc; + if (c == ' ' || c == '\n' || c == '\t') { + /* -1 for excluding the space in the word length */ + word[nw] = nc - 1; + + ++nw; + /* resetting the word-length for the next word */ + nc = 0; + } + } + + for (i = MAXWL; i >= 1; --i) { + for (j = 0; j <= nw; ++j) { + if (i <= word[j]) + putchar('*'); + else + putchar(' '); + } + putchar('\n'); + } + + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.13_his_horizontal.c b/source/cprogramming/chapter1/cprogs/ex_1.13_his_horizontal.c new file mode 100644 index 00000000..e5f9cd27 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.13_his_horizontal.c @@ -0,0 +1,19 @@ +/** + * + * Print a horizontal histogram of words in the input. + * + **/ + +#include + +int main(void) { + int c; + + while ((c = getchar()) != EOF) { + if (c == ' ' || c == '\n' || c == '\t') + putchar('\n'); + else + putchar('*'); + } + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.14_hist_freq.c b/source/cprogramming/chapter1/cprogs/ex_1.14_hist_freq.c new file mode 100644 index 00000000..1edfb71b --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.14_hist_freq.c @@ -0,0 +1,33 @@ +/** + * + * Histogram of Frequency of Different Characters in Input + * + **/ + +#include + +#define TOTAL_CHARS 128 /* Total Number of characters is 128: 0 - 127 */ + +int main(void) { + int c, i, j; + + int _char[TOTAL_CHARS]; + + for (i = 0; i < TOTAL_CHARS; ++i) { + _char[i] = 0; + } + + while ((c = getchar()) != EOF) { + _char[c] = _char[c] + 1; + } + + for (i = 0; i < TOTAL_CHARS; ++i) { + putchar(i); + + for (j = 0; j < _char[i]; ++j) + putchar('*'); + + putchar('\n'); + } + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c b/source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c new file mode 100644 index 00000000..e3cddba6 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c @@ -0,0 +1,51 @@ +/** + * + * Exercise 1.15 + * + * Temperature Conversion. Floating point, Symbolic Constant. Functions + * + **/ + +#include + +#define LOWER 0 +#define UPPER 300 +#define STEP 20 + +void fahr_to_celsius(void); + +void celsius_to_fahr(void); + +int main(void) { + int c; + + printf("Temperature Conversion Table\n"); + printf("1 - Fahrenheit to Celsius Conversion\n"); + printf("2 - Celsius to Fahrenheit Conversion\n"); + printf("- Enter your Choice\n"); + + c = getchar(); + + if (c == '1') + fahr_to_celsius(); + else if (c == '2') + celsius_to_fahr(); + else + printf("Invalid Choice\n"); + + return 0; +} + +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 celsius_to_fahr() { + float celsius; + + for (celsius = LOWER; celsius <= UPPER; celsius = celsius + STEP) + printf("%3.0f%6.1f\n", celsius, (9.0 * celsius) / 5.0 + 32); +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.16_longline.c b/source/cprogramming/chapter1/cprogs/ex_1.16_longline.c new file mode 100644 index 00000000..40be31e5 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.16_longline.c @@ -0,0 +1,87 @@ +/** + * Exercise 1.16 + * + * Write a program to print the length of an arbitrarily long input line + * and as much text as possible + * + **/ + +#include + +/* The size of the output that we would like */ +#define MAX 1000 + +/* define our functions*/ +int get_line(char arr[], int lim); + +void copy(char to[], const char from[]); + +int main() { + + int len, max; + char line[MAX]; + char longest[MAX]; + + max = 0; + while ((len = get_line(line, MAX)) > 0) { + + if (len > max) { + + max = len; + copy(longest, line); + } + } + + if (max > 0) { + + printf("length = %i, string=%s", max, longest); + } + + return 0; +} + +/* get a line in a character array */ +int get_line(char arr[], int lim) { + + int c, i; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) { + + arr[i] = c; + } + if (c == '\n') { + + arr[i] = c; + ++i; + + } else { + + /* Continue to count the length even if it is longer than the max */ + while ((c = getchar() != EOF) && c != '\n') { + + ++i; + } + + if (c == '\n') { + + arr[i] = c; + ++i; + } + } + + arr[i] = '\0'; + return i; +} + +/* copy one character array to another */ +void copy(char to[], const char from[]) { + + int i; + + i = 0; + + while ((to[i] = from[i]) != '\0') { + + ++i; + } +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c b/source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c new file mode 100644 index 00000000..5873a15f --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c @@ -0,0 +1,47 @@ +/** + * + * Exercise 1.17 - Program to print the length of all input lines greater + * than 80 characters. + * + **/ + +#include + +#define MAXLINE 1000 +#define LIMIT 80 + +/*** + * + * We call it _getline, for new getline so that it does not conflict with + * system function getline + * + ***/ + +int _getline(char line[], int lim); + +int main(void) { + int len; + char line[MAXLINE]; + + while ((len = _getline(line, MAXLINE)) > 0) { + if (len > LIMIT) + printf("%s", line); + } + + return 0; +} + +int _getline(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; + ++i; + } + 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 new file mode 100644 index 00000000..4728c4a9 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.18_remtrailbt.c @@ -0,0 +1,58 @@ +/** + * + * Exercise 1.18 - Write a Program to remove the trailing blanks and tabs + * from each input line and to delete entirely blank lines + * + **/ + +#include + +#define MAXLINE 1000 + +int _getline(char line[], int lim); + +int remove_trail(char rline[]); + +int main(void) { + int len; + char line[MAXLINE]; + + while ((len = _getline(line, MAXLINE)) > 0) + if (remove_trail(line) > 0) + printf("%s", line); + + return 0; +} + +int _getline(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; + ++i; + } + line[i] = '\0'; + + return i; +} + +/* To remove Trailing Blanks,tabs. Go to End and proceed backwards removing */ +int remove_trail(char rline[]) { + int i; + + for (i = 0; rline[i] != '\n'; ++i); + --i; /* To consider raw line without \n */ + + for (i > 0; ((rline[i] == ' ') || (rline[i] == '\t')); --i); /* Removing the Trailing Blanks and Tab Spaces */ + + if (i >= 0) /* Non Empty Line */ + { + ++i; + rline[i] = '\n'; + ++i; + 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 new file mode 100644 index 00000000..bf9509bf --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.19_reversestr.c @@ -0,0 +1,62 @@ +/** + * Exercise 1.19 - Write a function reverse that reverses the character + * string s; use it to write a program that reverses its input a line at a time. + * + **/ + +#include + +#define MAXLINE 1000 + +int _getline(char line[], int lim); + +void reverse(char rline[]); + +int main(void) { + int len; + char line[MAXLINE]; + + while ((len = _getline(line, MAXLINE)) > 0) { + reverse(line); + printf("%s", line); + } + + return 0; +} + +int _getline(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; + ++i; + } + line[i] = '\0'; + + return i; +} + +void reverse(char rline[]) { + int i, j; + char temp; + + for (i = 0; rline[i] != '\0'; ++i); + + --i; + + if (rline[i] == '\n') + --i; + + j = 0; + + while (j < i) { + temp = rline[j]; + rline[j] = rline[i]; + rline[i] = temp; + --i; + ++j; + } +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.20_detab.c b/source/cprogramming/chapter1/cprogs/ex_1.20_detab.c new file mode 100644 index 00000000..952abf99 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.20_detab.c @@ -0,0 +1,37 @@ +/** + * Exercise 1.20 + * + * Write a Program detab, which replaces tabs in the input with a proper + * number of blanks to spaces + **/ + +#include + +#define TABINC 8 + +int main(void) { + int nb, pos, c; + + nb = 0; + pos = 1; + + while ((c = getchar()) != EOF) { + if (c == '\t') { + nb = TABINC - ((pos - 1) % TABINC); + + while (nb > 0) { + putchar('#'); + ++pos; + --nb; + } + } else if (c == '\n') { + putchar(c); + pos = 1; + } else { + putchar(c); + ++pos; + } + } + + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.21_entab.c b/source/cprogramming/chapter1/cprogs/ex_1.21_entab.c new file mode 100644 index 00000000..9a65d76f --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.21_entab.c @@ -0,0 +1,46 @@ +/** + * + * Exercise 1.21 - 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. + * + **/ + +#include + +#define TABINC 8 + +int main(void) { + int nb, nt, pos, c; + + nb = 0; + nt = 0; + + for (pos = 1; (c = getchar()) != EOF; ++pos) + if (c == ' ') { + if ((pos % TABINC) != 0) + ++nb; + else { + nb = 0; + ++nt; + } + } else { + for (; nt > 0; --nt) + putchar('\t'); + if (c == '\t') + nb = 0; + else + for (; nb > 0; --nb) + putchar(' '); + + putchar(c); + + if (c == '\n') + pos = 0; + else if (c == '\t') + pos = pos + (TABINC - (pos - 1) % TABINC) - 1; + } + + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.22_fold.c b/source/cprogramming/chapter1/cprogs/ex_1.22_fold.c new file mode 100644 index 00000000..2a558507 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.22_fold.c @@ -0,0 +1,65 @@ +#include + +#define MAXCOL 35 /* folded line length */ +#define TABVAL 8 /* standard tab length */ +#define CURTAB(c) (TABVAL - ((c) % TABVAL)) /* current tab size */ +#define NO_BLANK -1 /* signifies no blank found */ + +/* 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) { + int c; /* character variable */ + int i, j; /* indexing variable(s) */ + int pos; /* current position in array */ + int col; /* current column of output */ + int lbc; /* last blank character position */ + char line[MAXCOL + 1]; /* fold array */ + + pos = col = 0; + while ((c = getchar()) != EOF) { + /* process line array, keep track of line length by columns */ + line[pos++] = c; + col += (c == '\t') ? CURTAB(col) : 1; + + /* create fold */ + if (col >= MAXCOL || c == '\n') { + line[pos] = '\0'; + + if ((lbc = lastblank(line, pos)) == NO_BLANK) { + /* split word if no blank characters */ + for (i = 0; i < pos; ++i) + putchar(line[i]); + /* reset column value and array position */ + col = pos = 0; + } else { + /* print array up until last blank character */ + for (i = 0; i < lbc; ++i) + putchar(line[i]); + /* feed remaining characters into buffer */ + for (i = 0, j = lbc + 1, col = 0; j < pos; ++i, ++j) { + line[i] = line[j]; + /* set new column value */ + col += (c == '\t') ? CURTAB(col) : 1; + } + /* set array position after remaining characters */ + pos = i; + } + /* finish folded line with newline character */ + putchar('\n'); + } + } + + return 0; +} \ 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 new file mode 100644 index 00000000..547dc0e1 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.23_remcomments.c @@ -0,0 +1,72 @@ +/* Exercise 1.23 + * + * Program to remove comments from a C Program. + * + * Program should echo quotes and character constants properly + * C comments do not nest + * + */ + +#include + +void rcomment(int c); + +void incomment(void); + +void echo_quote(int c); + +int main(void) { + int c, d; + + printf(" To Check /* Quoted String */ \n"); + + while ((c = getchar()) != EOF) + rcomment(c); + + return 0; +} + +void rcomment(int c) { + int d; + + if (c == '/') { + if ((d = getchar()) == '*') + incomment(); + else if (d == '/') { + putchar(c); + rcomment(d); + } else { + putchar(c); + putchar(d); + } + } else if (c == '\'' || c == '"') + echo_quote(c); + else + putchar(c); +} + +void incomment() { + int c, d; + + c = getchar(); + d = getchar(); + + while (c != '*' || d != '/') { + c = d; + d = getchar(); + } +} + +void echo_quote(int c) { + int d; + + putchar(c); + + while ((d = getchar()) != c) { + putchar(d); + + if (d == '\\') + putchar(getchar()); + } + putchar(d); +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c b/source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c new file mode 100644 index 00000000..f07012f7 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c @@ -0,0 +1,94 @@ +/** + * + * Exercise 1.24 - Syntax Errors. + * + * Program to check rudimentary syntax errors like un-match braces, + * brackets or parenthesis. + * + **/ + +#include + +int brace, brack, paren; + +void incomment(); + +void inquote(int c); + +void search(int c); + +int main(void) { + int c; + + extern int brace, brack, paren; + + while ((c = getchar()) != EOF) + if (c == '/') + if ((c = getchar()) == '*') + incomment(); + else + search(c); + else if (c == '\'' || c == '"') + inquote(c); + else + search(c); + + if (brace < 0) { + printf("Unmatched Braces\n"); + brace = 0; + } else if (brack < 0) { + printf("Unmatched brackets\n"); + brack = 0; + } else if (paren < 0) { + printf("Unmatched parenthesis\n"); + paren = 0; + } + + if (brace > 0) + printf("Unmatched braces\n"); + else if (brack > 0) + printf("Unmatched brackets\n"); + else if (paren > 0) + printf("Unmatched parenthesis\n"); + + return 0; +} + +void incomment() { + int c, d; + + c = getchar(); + d = getchar(); + + while (c != '*' || d != '/') { + c = d; + d = getchar(); + } +} + +void inquote(int c) { + int d; + + putchar(c); + + while ((d = getchar()) != c) + if (d == '\\') + getchar(); +} + +void search(int c) { + extern int brace, brack, paren; + + if (c == '{') + --brace; + else if (c == '}') + ++brace; + else if (c == '[') + --brack; + else if (c == ']') + ++brack; + else if (c == '(') + --paren; + else if (c == ')') + ++paren; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.3_fahr2celheading.c b/source/cprogramming/chapter1/cprogs/ex_1.3_fahr2celheading.c new file mode 100644 index 00000000..522682e3 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.3_fahr2celheading.c @@ -0,0 +1,34 @@ +/*** + * + * Exercise 1-3. Modify the temperature conversion program, + * Fahrenheit to Celsius, to print a heading above the table. + * + * print Fahrenheit-Celsius table for fahr = 0, 20, ..., 300; + * floating-point version. + * + ***/ + +#include + +int main(void) { + printf("A program print Fahrenheit-Celsius\n"); + + float fahr, celsius; + int lower, upper, step; + + lower = 0; + upper = 300; + step = 20; + + fahr = lower; + + printf("Fahr\tCelsius\t \n"); + + while (fahr <= upper) { + celsius = (5.0 / 9.0) * (fahr - 32.0); + printf("%4.0f %10.1f\n", fahr, celsius); + fahr = fahr + step; + } + + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.4_cel2fahr.c b/source/cprogramming/chapter1/cprogs/ex_1.4_cel2fahr.c new file mode 100644 index 00000000..a5f46bbe --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.4_cel2fahr.c @@ -0,0 +1,27 @@ +/*** + * + * Temperature Conversion Program, Celsius to Fahrenheit! + * + * print Fahrenheit-Celsius table for fahr = 0,20 ... 300 + * + ***/ + +#include + +int main(void) { + float fahr, celsius; + int lower, upper, step; + + lower = 0; + upper = 300; + step = 20; + + printf("C F\n\n"); + celsius = lower; + while (celsius <= upper) { + fahr = (9.0 / 5.0) * celsius + 32.0; + printf("%3.0f %6.1f\n", celsius, fahr); + celsius = celsius + step; + } + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c b/source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c new file mode 100644 index 00000000..1bf08ff7 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c @@ -0,0 +1,29 @@ +/*** + * + * Temperature Conversion Program, Celsius to Fahrenheit! + * + * print Fahrenheit-Celsius table for fahr = 0,20 ... 300 + * + ***/ + +#include + +int main(void) { + float fahr, celsius; + int lower, upper, step; + + lower = 0; + upper = 300; + step = 20; + + printf("C F\n\n"); + celsius = upper; + + while (celsius >= lower) { + fahr = (float) ((9.0 / 5.0) * celsius + 32.0); + printf("%3.0f %6.1f\n", celsius, fahr); + celsius = celsius - step; + } + + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.6_verifyeof.c b/source/cprogramming/chapter1/cprogs/ex_1.6_verifyeof.c new file mode 100644 index 00000000..e9224ea6 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.6_verifyeof.c @@ -0,0 +1,17 @@ +/** + * Exercise 1.6 - Verify that the expression getchar() != EOF is 0 or 1 + * + **/ + +#include + +int main(int argc, char *argv[]) { + int c; + + while ((c = getchar()) != EOF) { + printf("%d ", c != EOF); + putchar(c); + } + + printf("\n%d\n", c != EOF); +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.7_eofval.c b/source/cprogramming/chapter1/cprogs/ex_1.7_eofval.c new file mode 100644 index 00000000..5231c129 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.7_eofval.c @@ -0,0 +1,11 @@ +/** + * Program to print the value of EOF. EOF is a macro defined in stdio.h + * + **/ + +#include + +int main(void) { + printf("The value of EOF is %d Assuming senthil is a total cupper.", EOF); + return 0; +} 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 new file mode 100644 index 00000000..74ea77cd --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.8_count_blanks_etc.c @@ -0,0 +1,26 @@ +/*** + * + * Write a program to count blanks, tabs and newlines. + * + **/ + +#include + +int main() { + int c, blanks, tabs, newlines; + + blanks = tabs = newlines = 0; + + while ((c = getchar()) != EOF) { + if (c == ' ') + ++blanks; + if (c == '\t') + ++tabs; + if (c == '\n') + ++newlines; + } + + printf("Blanks: %d\n", blanks); + printf("Tabs: %d\n", tabs); + printf("Newlines: %d\n", newlines); +} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c b/source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c new file mode 100644 index 00000000..904081c8 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c @@ -0,0 +1,24 @@ +/** + * 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 + +#define NONBLANK '-' + +int main(void) { + int c, lastc; + + lastc = NONBLANK; + + while ((c = getchar()) != EOF) { + if (c == ' ') { + if (lastc != ' ') + putchar(c); + } else + putchar(c); + lastc = c; + } + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c b/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c new file mode 100644 index 00000000..44023f89 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c @@ -0,0 +1,47 @@ +#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 */ + + +/* 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 */ +int main() { + int len; + extern int max; + extern char longest[]; + max = 0; + while ((len = mgetline()) > 0) + if (len > max) { + max = len; + copy(); + } + if (max > 0) /* there was a line */ + printf("%s", longest); + return 0; +} \ 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 new file mode 100644 index 00000000..412103bd --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c @@ -0,0 +1,7 @@ +/* First Program in K&R. print hello,world */ + +#include + +int main() { + printf("hello, world\n"); +} diff --git a/source/cprogramming/chapter1/cprogs/sec_1.2_fahr2cel.c b/source/cprogramming/chapter1/cprogs/sec_1.2_fahr2cel.c new file mode 100644 index 00000000..667b6536 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.2_fahr2cel.c @@ -0,0 +1,24 @@ +/* Temperature Conversion Program, Fahrenheit to Celsius */ + +#include + +/* print Fahrenheit-Celsius table for fahr = 0,20 ... 300 */ + +int main() { + int lower, upper, step; + int celsius, fahr; + + lower = 0; + upper = 300; + step = 20; + + fahr = lower; + + while (fahr <= upper) { + celsius = 5 * (fahr - 32) / 9; + printf("%d\t%d\n", fahr, celsius); + fahr = fahr + step; + } + + return 0; +} diff --git a/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c b/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c new file mode 100644 index 00000000..926d982b --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c @@ -0,0 +1,8 @@ +#include + +/* print Fahrenheit-Celsius table */ +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 new file mode 100644 index 00000000..c188f89b --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c @@ -0,0 +1,11 @@ +#include + +#define LOWER 0 +#define UPPER 300 +#define STEP 20 + +int main() { + int fahr; + for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) + printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32)); +} 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 new file mode 100644 index 00000000..04f2e966 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.1_file_copying.c @@ -0,0 +1,10 @@ +#include + +int main() { + int c; + c = getchar(); + while (c != EOF) { + putchar(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 new file mode 100644 index 00000000..87264ab9 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting.c @@ -0,0 +1,10 @@ +#include + +/* count characters in input; 1st version */ +int main() { + long nc; + nc = 0; + while (getchar() != EOF) + ++nc; + printf("%ld\n", nc); +} 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 new file mode 100644 index 00000000..8ec8df2f --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting2.c @@ -0,0 +1,8 @@ +#include + +/* count characters in input; 2nd version */ +int main() { + double 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 new file mode 100644 index 00000000..907a5084 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c @@ -0,0 +1,11 @@ +#include + +/* count lines in input */ +int main() { + int c, nl; + nl = 0; + while ((c = getchar()) != EOF) + if (c == '\n') + ++nl; + printf("%d\n", nl); +} 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 new file mode 100644 index 00000000..5bfe4801 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c @@ -0,0 +1,23 @@ +#include + +#define IN 1 /* inside a word */ +#define OUT 0 /* outside a word */ + +/* count lines, words, and characters in input */ +int main() { + int c, nl, nw, nc, state; + state = OUT; + nl = nw = nc = 0; + while ((c = getchar()) != EOF) { + ++nc; + if (c == '\n') + ++nl; + if (c == ' ' || c == '\n' || c == '\t') + state = OUT; + else if (state == OUT) { + state = IN; + ++nw; + } + } + printf("%d %d %d\n", nl, nw, nc); +} diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c b/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c new file mode 100644 index 00000000..04f2e966 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c @@ -0,0 +1,10 @@ +#include + +int main() { + int c; + c = getchar(); + while (c != EOF) { + putchar(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 new file mode 100644 index 00000000..20bd0dd3 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c @@ -0,0 +1,22 @@ +#include + +/* count digits, white space, others */ +int main() { + int c, i, nwhite, nother; + int ndigit[10]; + nwhite = nother = 0; + for (i = 0; i < 10; ++i) + ndigit[i] = 0; + while ((c = getchar()) != EOF) { + if (c >= '0' && c <= '9') + ++ndigit[c - '0']; + else if (c == ' ' || c == '\n' || c == '\t') + ++nwhite; + else + ++nother; + printf("digits ="); + for (i = 0; i < 10; ++i) + printf(" %d", ndigit[i]); + printf(", white space = %d, other = %d\n", nwhite, nother); + } +} diff --git a/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c b/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c new file mode 100644 index 00000000..c8db6ff5 --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c @@ -0,0 +1,20 @@ +#include + +int power(int base, int n); + +/* test power function */ +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; + p = 1; + 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 new file mode 100644 index 00000000..70b9814a --- /dev/null +++ b/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c @@ -0,0 +1,45 @@ +#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 */ +int main() { + int len; /* current line length */ + int max; /* maximum length seen so far */ + char line[MAXLINE]; /* current input line */ + char longest[MAXLINE]; /* longest line saved here */ + max = 0; + while ((len = mgetline(line, MAXLINE)) > 0) + if (len > max) { + max = len; + copy(longest, line); + } + if (max > 0) /* there was a line */ + printf("%s", longest); + return 0; +} + +/* mgetline: read a line into line, return length */ +int mgetline(char line[], int maxline) { + int c, i; + 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: copy 'from' into 'to'; assume to is big enough */ +void copy(char to[], char from[]) { + int i; + i = 0; + while ((to[i] = from[i]) != '\0') + ++i; +} diff --git a/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst b/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst new file mode 100644 index 00000000..8beeb648 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst @@ -0,0 +1,24 @@ +======================================================= +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:: cprogs/ex_1.10_tbsblnkspaces.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.11_test_word_count.rst b/source/cprogramming/chapter1/ex_1.11_test_word_count.rst new file mode 100644 index 00000000..2d97340e --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.11_test_word_count.rst @@ -0,0 +1,32 @@ +======================================= +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:: cprogs/sec_1.5.4_word_counting.c + :language: c + +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. \ 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 new file mode 100644 index 00000000..d6e122e6 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst @@ -0,0 +1,91 @@ +==================================== +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:: cprogs/ex_1.13.2_his_vertical.c + :language: c + + +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. \ No newline at end of file diff --git a/source/cprogramming/chapter1/ex_1.13_his_horizontal.rst b/source/cprogramming/chapter1/ex_1.13_his_horizontal.rst new file mode 100644 index 00000000..27dbe6b3 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.13_his_horizontal.rst @@ -0,0 +1,34 @@ +==================================== +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:: cprogs/ex_1.13_his_horizontal.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.14_hist_freq.rst b/source/cprogramming/chapter1/ex_1.14_hist_freq.rst new file mode 100644 index 00000000..34810315 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.14_hist_freq.rst @@ -0,0 +1,29 @@ +==================================================== +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:: cprogs/ex_1.14_hist_freq.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.15_tempconv.rst b/source/cprogramming/chapter1/ex_1.15_tempconv.rst new file mode 100644 index 00000000..19ae98e1 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.15_tempconv.rst @@ -0,0 +1,29 @@ +========================================================= +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:: cprogs/ex_1.15_tempconv.c + :language: c + +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 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.16_longline.rst b/source/cprogramming/chapter1/ex_1.16_longline.rst new file mode 100644 index 00000000..dec4debb --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.16_longline.rst @@ -0,0 +1,32 @@ +========================================================= +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:: cprogs/ex_1.16_longline.c + :language: c + + +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. + diff --git a/source/cprogramming/chapter1/ex_1.17_lengt80.rst b/source/cprogramming/chapter1/ex_1.17_lengt80.rst new file mode 100644 index 00000000..55d79a51 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.17_lengt80.rst @@ -0,0 +1,29 @@ +========================================================= +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:: cprogs/ex_1.17_lengt80.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst b/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst new file mode 100644 index 00000000..10d63943 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst @@ -0,0 +1,24 @@ +=============================================== +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:: cprogs/ex_1.18_remtrailbt.c + :language: c + +Explanation +=========== + +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.19_reversestr.rst b/source/cprogramming/chapter1/ex_1.19_reversestr.rst new file mode 100644 index 00000000..d7d3a9a5 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.19_reversestr.rst @@ -0,0 +1,45 @@ +================================ +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:: cprogs/ex_1.19_reversestr.c + :language: c + + +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; + } + diff --git a/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst b/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst new file mode 100644 index 00000000..cd641c13 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst @@ -0,0 +1,48 @@ +=================================== +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:: cprogs/sec_1.1_helloworld.c + :language: c + +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 diff --git a/source/cprogramming/chapter1/ex_1.20_detab.rst b/source/cprogramming/chapter1/ex_1.20_detab.rst new file mode 100644 index 00000000..4960c3c3 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.20_detab.rst @@ -0,0 +1,67 @@ +================================================ +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:: cprogs/ex_1.20_detab.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.21_entab.rst b/source/cprogramming/chapter1/ex_1.21_entab.rst new file mode 100644 index 00000000..0c7fd485 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.21_entab.rst @@ -0,0 +1,41 @@ +================================================ +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:: cprogs/ex_1.21_entab.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.22_fold.rst b/source/cprogramming/chapter1/ex_1.22_fold.rst new file mode 100644 index 00000000..ab018d23 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.22_fold.rst @@ -0,0 +1,60 @@ +=============================== +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:: cprogs/ex_1.22_fold.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.23_remcomments.rst b/source/cprogramming/chapter1/ex_1.23_remcomments.rst new file mode 100644 index 00000000..a9ded0e9 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.23_remcomments.rst @@ -0,0 +1,31 @@ +================================================ +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:: cprogs/ex_1.23_remcomments.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.24_synerrors.rst b/source/cprogramming/chapter1/ex_1.24_synerrors.rst new file mode 100644 index 00000000..93b027ec --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.24_synerrors.rst @@ -0,0 +1,38 @@ +============================================================== +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:: cprogs/ex_1.24_synerrors.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst b/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst new file mode 100644 index 00000000..2915cf1f --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst @@ -0,0 +1,27 @@ +==================================== +Exercise 1.3 - Temperature Convertor +==================================== + +Question +-------- + + +Modify the temperature conversion program to print a heading above the table. + +Solution +-------- + +.. literalinclude:: cprogs/ex_1.3_fahr2celheading.c + :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. diff --git a/source/cprogramming/chapter1/ex_1.4_cel2fahr.rst b/source/cprogramming/chapter1/ex_1.4_cel2fahr.rst new file mode 100644 index 00000000..a2b64594 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.4_cel2fahr.rst @@ -0,0 +1,31 @@ +==================================== +Exercise 1.4 - Temperature Convertor +==================================== + +Question +-------- + + +Write a program to print the corresponding Celsius to Fahrenheit table. + + +Solution +-------- + +.. literalinclude:: cprogs/ex_1.4_cel2fahr.c + :language: c + +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. + diff --git a/source/cprogramming/chapter1/ex_1.5_reverse.rst b/source/cprogramming/chapter1/ex_1.5_reverse.rst new file mode 100644 index 00000000..9ceba9dd --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.5_reverse.rst @@ -0,0 +1,29 @@ +=============================================== +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:: cprogs/ex_1.5_reverse.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/ex_1.6_verifyeof.rst b/source/cprogramming/chapter1/ex_1.6_verifyeof.rst new file mode 100644 index 00000000..81240918 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.6_verifyeof.rst @@ -0,0 +1,41 @@ +====================================== +Exercise 1.6 - Verify the value of EOF +====================================== + +Question +-------- + +Verify the expression `getchar() !=EOF` is 0 or 1. + +Solution +-------- + +.. literalinclude:: cprogs/ex_1.6_verifyeof.c + :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. + +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. diff --git a/source/cprogramming/chapter1/ex_1.7_eofval.rst b/source/cprogramming/chapter1/ex_1.7_eofval.rst new file mode 100644 index 00000000..2f740f26 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.7_eofval.rst @@ -0,0 +1,21 @@ +=========================== +Exercise 1.7 - Value of EOF +=========================== + +Question +-------- + +Write a Program to print the value of EOF. + +Solution +-------- + +.. literalinclude:: cprogs/ex_1.7_eofval.c + :language: c + +Explanation +=========== + +1. Since EOF is an integer, we can print it with %d format in the printf. 2. EOF +value is printed as -1. + diff --git a/source/cprogramming/chapter1/ex_1.8_count_blanks_etc.rst b/source/cprogramming/chapter1/ex_1.8_count_blanks_etc.rst new file mode 100644 index 00000000..a33d3c63 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.8_count_blanks_etc.rst @@ -0,0 +1,30 @@ +============================================== +Exercise 1.8 - Count blanks, tabs and newlines +============================================== + +Question +-------- + +Write a program to count blanks, tabs, and newlines. + +Solution +-------- + +.. literalinclude:: cprogs/ex_1.8_count_blanks_etc.c + :language: c + +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 + diff --git a/source/cprogramming/chapter1/ex_1.9_sinblank.rst b/source/cprogramming/chapter1/ex_1.9_sinblank.rst new file mode 100644 index 00000000..c5c16b38 --- /dev/null +++ b/source/cprogramming/chapter1/ex_1.9_sinblank.rst @@ -0,0 +1,32 @@ +=========================================================== +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:: cprogs/ex_1.9_sinblank.c + :language: c + +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)`. + diff --git a/source/cprogramming/chapter1/index.rst b/source/cprogramming/chapter1/index.rst new file mode 100644 index 00000000..5a19106a --- /dev/null +++ b/source/cprogramming/chapter1/index.rst @@ -0,0 +1,44 @@ +========= +Chapter 1 +========= + +.. toctree:: + :maxdepth: 1 + + sec_1.1_helloworld + ex_1.1_exp_helloworld + sec_1.2_fahr2cel + sec_1.3_for_loop + ex_1.3_fahr2celheading + sec_1.4_symbolic + ex_1.4_cel2fahr + sec_1.5.1_file_copying + sec_1.5.2_character_counting + sec_1.5.2_character_counting2 + sec_1.5.3_line_counting + sec_1.5.4_word_counting + sec_1.5_inp2ou + ex_1.5_reverse + sec_1.6_arrays + ex_1.6_verifyeof + sec_1.7_functions + ex_1.7_eofval + ex_1.8_count_blanks_etc + sec_1.9_character_arrays + ex_1.9_sinblank + sec_1.10_external_variables + ex_1.10_tbsblnkspaces + ex_1.11_test_word_count + ex_1.13.2_his_vertical + ex_1.13_his_horizontal + ex_1.14_hist_freq + ex_1.15_tempconv + ex_1.16_longline + ex_1.17_lengt80 + ex_1.18_remtrailbt + ex_1.19_reversestr + ex_1.20_detab + ex_1.21_entab + ex_1.22_fold + ex_1.23_remcomments + ex_1.24_synerrors \ No newline at end of file diff --git a/source/cprogramming/chapter1/sec_1.10_external_variables.rst b/source/cprogramming/chapter1/sec_1.10_external_variables.rst new file mode 100644 index 00000000..1a8dcabc --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.10_external_variables.rst @@ -0,0 +1,24 @@ +========================================= +Section 1.10 External Variables and Scope +========================================= + +Program +======= + +.. literalinclude:: cprogs/sec_1.10_external_variables.c + :language: c + +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. + diff --git a/source/cprogramming/chapter1/sec_1.1_helloworld.rst b/source/cprogramming/chapter1/sec_1.1_helloworld.rst new file mode 100644 index 00000000..462db5d7 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.1_helloworld.rst @@ -0,0 +1,30 @@ +=========================== +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:: cprogs/sec_1.1_helloworld.c + :language: c + +Extras +====== + +What really happens when you run hello world program? + +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 new file mode 100644 index 00000000..6ae4202a --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst @@ -0,0 +1,33 @@ +================================================ +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:: cprogs/sec_1.2_fahr2cel.c + :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 out put. diff --git a/source/cprogramming/chapter1/sec_1.3_for_loop.rst b/source/cprogramming/chapter1/sec_1.3_for_loop.rst new file mode 100644 index 00000000..e863d451 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.3_for_loop.rst @@ -0,0 +1,27 @@ +============================= +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:: cprogs/sec_1.3_for_loop.c + :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) using a for loop :: + + 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/sec_1.4_symbolic.rst b/source/cprogramming/chapter1/sec_1.4_symbolic.rst new file mode 100644 index 00000000..481b9b75 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.4_symbolic.rst @@ -0,0 +1,23 @@ +============================== +Section 1.4 Symbolic Constants +============================== + +Program +======= + +.. literalinclude:: cprogs/sec_1.4_symbolic.c + :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). 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. \ 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 new file mode 100644 index 00000000..f0ec240f --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst @@ -0,0 +1,10 @@ +========================== +Section 1.5.1 File Copying +========================== + +Program +------- + + +.. literalinclude:: cprogs/sec_1.5.1_file_copying.c + :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 new file mode 100644 index 00000000..c9719190 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst @@ -0,0 +1,23 @@ +================================ +Section 1.5.2 Character Counting +================================ + + +Program +------- + + +.. literalinclude:: cprogs/sec_1.5.2_character_counting.c + :language: c + +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. + +---- + +This document was updated on |today| diff --git a/source/cprogramming/chapter1/sec_1.5.2_character_counting2.rst b/source/cprogramming/chapter1/sec_1.5.2_character_counting2.rst new file mode 100644 index 00000000..63ee1c05 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.5.2_character_counting2.rst @@ -0,0 +1,25 @@ +================================= +Section 1.5.2 Character Counting2 +================================= + + +Program +------- + + +.. literalinclude:: cprogs/sec_1.5.2_character_counting2.c + :language: c + + +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. + + +---- + +This document was updated on |today| diff --git a/source/cprogramming/chapter1/sec_1.5.3_line_counting.rst b/source/cprogramming/chapter1/sec_1.5.3_line_counting.rst new file mode 100644 index 00000000..c143a3e6 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.5.3_line_counting.rst @@ -0,0 +1,22 @@ +=========================== +Section 1.5.3 Line Counting +=========================== + +Program +======= + +.. literalinclude:: cprogs/sec_1.5.3_line_counting.c + :language: c + +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. + +---- + +This document was updated on |today| diff --git a/source/cprogramming/sec_1.5.4_word_counting.rst b/source/cprogramming/chapter1/sec_1.5.4_word_counting.rst similarity index 75% rename from source/cprogramming/sec_1.5.4_word_counting.rst rename to source/cprogramming/chapter1/sec_1.5.4_word_counting.rst index c5a7f994..b22ac39b 100644 --- a/source/cprogramming/sec_1.5.4_word_counting.rst +++ b/source/cprogramming/chapter1/sec_1.5.4_word_counting.rst @@ -6,14 +6,9 @@ Section 1.5.4 Word Counting Program ======= -.. literalinclude:: ../../languages/cprogs/sec_1.5.4_word_counting.c +.. literalinclude:: 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 =========== @@ -30,9 +25,3 @@ 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/chapter1/sec_1.5_inp2ou.rst b/source/cprogramming/chapter1/sec_1.5_inp2ou.rst new file mode 100644 index 00000000..e38426db --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.5_inp2ou.rst @@ -0,0 +1,24 @@ +====================================== +Section 1.5 Character Input and Output +====================================== + +Program +------- + +.. literalinclude:: cprogs/sec_1.5_inp2ou.c + :language: c + + +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. diff --git a/source/cprogramming/chapter1/sec_1.6_arrays.rst b/source/cprogramming/chapter1/sec_1.6_arrays.rst new file mode 100644 index 00000000..bd1a4119 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.6_arrays.rst @@ -0,0 +1,24 @@ +================== +Section 1.6 Arrays +================== + + +Program +======= + +.. literalinclude:: cprogs/sec_1.6_arrays.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/sec_1.7_functions.rst b/source/cprogramming/chapter1/sec_1.7_functions.rst new file mode 100644 index 00000000..be4778d8 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.7_functions.rst @@ -0,0 +1,18 @@ +===================== +Section 1.7 Functions +===================== + + +Program +======= + +.. literalinclude:: cprogs/sec_1.7_functions.c + :language: c + +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. diff --git a/source/cprogramming/chapter1/sec_1.9_character_arrays.rst b/source/cprogramming/chapter1/sec_1.9_character_arrays.rst new file mode 100644 index 00000000..81a14550 --- /dev/null +++ b/source/cprogramming/chapter1/sec_1.9_character_arrays.rst @@ -0,0 +1,23 @@ +============================ +Section 1.9 Character Arrays +============================ + + +Program +======= + +.. literalinclude:: cprogs/sec_1.9_character_arrays.c + :language: c + +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. + diff --git a/source/cprogramming/chapter2/cprogs/ex_2.10_lowercondit.c b/source/cprogramming/chapter2/cprogs/ex_2.10_lowercondit.c new file mode 100644 index 00000000..c976a536 --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.10_lowercondit.c @@ -0,0 +1,15 @@ +/* Function lower(c) using conditional expression */ + +#include + +int lower(int c); + +int main(void) { + int c; + + while ((c = getchar()) != EOF) { + putchar(lower(c)); + } +} + +int lower(int c) { return c >= 'A' && c <= 'Z' ? c + 'a' - 'A' : 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 new file mode 100644 index 00000000..f0f4539f --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.2_getline_without_and_or.c @@ -0,0 +1,61 @@ +/** + * Exercise 2.2 + * + * Write a loop equivalent for getline without using && and || + * This program prints the longest line in the given inputs + * + **/ + +#include + +#define MAXLINE 1000 + +int mgetline(char line[], int lim); + +void copy(char to[], const char from[]); + +int main(void) { + int len, max; + char line[MAXLINE], maxline[MAXLINE]; + + max = 0; + + while ((len = mgetline(line, MAXLINE)) > 0) { + if (len > max) { + max = len; + copy(maxline, line); + } + } + + if (max > 0) + printf("%s", maxline); +} + +int mgetline(char line[], int lim) { + int i, c; + + for (i = 0; i < lim - 1; ++i) { + c = getchar(); + if (c == EOF) + break; + if (c == '\n') + break; + line[i] = c; + } + + if (c == '\n') { + line[i] = c; + ++i; + } + + line[i] = '\0'; + return i; +} + +void copy(char to[], const char from[]) { + int i; + i = 0; + + while ((to[i] = from[i]) != '\0') + ++i; +} 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 new file mode 100644 index 00000000..3c91036f --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c @@ -0,0 +1,57 @@ +/** + * 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. + * 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 s[], int lim); + +void squeeze(char s1[], const char s2[]); + +int main(void) { + char s1[MAXLINE], s2[MAXLINE]; + mgetline(s1, MAXLINE); + mgetline(s2, MAXLINE); + + squeeze(s1, s2); + + printf("\n%s\n", s1); + + 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'; + + return i; +} + +void squeeze(char s1[], const char s2[]) { + int i, j, k; + k = 0; + + for (i = 0; s1[i] != '\0'; ++i) { + for (j = 0; (s1[i] != s2[j]) && s2[j] != '\0'; ++j) + ; + if (s2[j] == '\0') + s1[k++] = s1[i]; + } + + 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 new file mode 100644 index 00000000..5c9600b3 --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.7_invert.c @@ -0,0 +1,18 @@ +/** + * + * Exercise 2.7 + * + * Write a function invert(x,p,n) that returns x with n bit starting at p + * inverted . + * + **/ + +#include + +unsigned invert(unsigned x, int p, int n); + +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 new file mode 100644 index 00000000..61e93a76 --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.8_rightrot.c @@ -0,0 +1,37 @@ +/* Write a function rightrot(x,n) that returns the value of the integer x + * rotated to rightby n bit positions */ + +#include + +unsigned rightrot(unsigned x, int n); + +int main(void) { + printf("%u", (unsigned)rightrot((unsigned)8, (int)1)); + + return 0; +} + +/* rightrot: rotate x to right by n bit positions */ + +unsigned rightrot(unsigned x, int n) { + int wordlength(void); + unsigned rbit; /* rightmost bit */ + + rbit = x << (wordlength() - n); + + x = x >> n; + x = x | rbit; + + return x; +} + +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 new file mode 100644 index 00000000..485f405d --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c @@ -0,0 +1,18 @@ +/* In twos complement number systems, x &= (x-1) deletes the rightmost 1 bit in + * x. Explain why? Use this to right a faster version of bitcount. Bitcount + * program counts the number of 1 bits in the integer */ + +#include + +int bitcount(unsigned x) { + int b; + + for (b = 0; x != 0; x &= x - 1) + ++b; + + return b; +} + +int main(void) { + printf("%d", bitcount((unsigned) 12)); +} \ No newline at end of file diff --git a/source/cprogramming/chapter2/ex_2.10_lowercondit.rst b/source/cprogramming/chapter2/ex_2.10_lowercondit.rst new file mode 100644 index 00000000..b7f99fb9 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.10_lowercondit.rst @@ -0,0 +1,32 @@ +================================================ +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:: cprogs/ex_2.10_lowercondit.c + :language: c + +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; diff --git a/source/cprogramming/chapter2/ex_2.1_cal_limits.rst b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst new file mode 100644 index 00000000..42c1dc30 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst @@ -0,0 +1,147 @@ +=============================== +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:: cprogs/ex_2.1_cal_limits.c + :language: c + +Explanation +=========== + + +The execution of the above program will give:: + + 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. + +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 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 new file mode 100644 index 00000000..f943bd19 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst @@ -0,0 +1,47 @@ +======================================================= +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:: cprogs/ex_2.2_getline_without_and_or.c + :language: c + + +Explanation +=========== + +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. + +:: + + 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. diff --git a/source/cprogramming/chapter2/ex_2.3_htoi.rst b/source/cprogramming/chapter2/ex_2.3_htoi.rst new file mode 100644 index 00000000..520afa17 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.3_htoi.rst @@ -0,0 +1,106 @@ +========================================================== +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:: cprogs/ex_2.3_htoi.c + :language: c + +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. + +.. code-block:: c + + if(inhex == YES) + n = 16 * n + hexdigit; + +For example to convert **0XAF**. + +.. 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 new file mode 100644 index 00000000..4a402b69 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.4_squeezess.rst @@ -0,0 +1,60 @@ +============================================================ +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:: cprogs/ex_2.4_squeezess.c + :language: c + +Explanation +=========== + +Let's take the two inputs strings as: + +.. code-block:: bash + + HelloWorld + ol + +Our desired output is + +.. 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 + +.. code-block:: c + + 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. + +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 new file mode 100644 index 00000000..e7f8b697 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.5_any.rst @@ -0,0 +1,46 @@ +====================================================================== +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:: cprogs/ex_2.5_any.c + :language: c + +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. + + +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 new file mode 100644 index 00000000..e58f0cf7 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.6_setbits.rst @@ -0,0 +1,52 @@ +=========================================== +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:: cprogs/ex_2.6_setbits.c + :language: c + +Explanation +=========== + +The setbits function takes 4 inputs: + +- x: The original number we want to modify +- p: The position where we want to make changes (counting from right, starting at 0) +- n: How many bits we want to replace +- y: The number we want to take bits from + + +The function replaces n bits in x, starting at position p, with the rightmost n bits from y. + +:: + + setbits(0x37, 3, 2, 0x4E) // Returns 0x3B + + - x = 0x37 = 0011 0111 in binary + - Starting at position 3 (p=3) + - We want to change 2 bits (n=2) + - Taking (2 ) bits from y = 0x4E = 0100 1110 + + The function: + + - Takes the rightmost 2 bits from y (10) + - Places them at position 3 in x + + :: + + Original: 0011 0111 + Result: 0011 1011 (0x3B) + +Visualization +============= + +.. raw:: html + + + diff --git a/source/cprogramming/chapter2/ex_2.7_invert.rst b/source/cprogramming/chapter2/ex_2.7_invert.rst new file mode 100644 index 00000000..37816dfc --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.7_invert.rst @@ -0,0 +1,55 @@ +================================================== +Exercise 2.7-Setting bits at a position n Inverted +================================================== + +Question +======== + +Write a function invert(x,p,n) that returns x with the n bits that begin at +position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others +unchanged. + +.. literalinclude:: cprogs/ex_2.7_invert.c + :language: c + +Explanation +=========== + +Let's take n as 3:: + + ~(~0 << n) = ~(~0 << 3) + = ~(1111 1111 << 3) + = ~(1 1111 000 << 3) + = ~(1111 1000) + = 0000 0111 + + This sets the last n bits to 1 and rest to 0 + + The given position p 0 indexed and the number of bits, n is 1 indexed. + So in order to change the bits starting at position, p, we need to shift our + streams 1s to position p and we accomplish that by left shifting the stream of 1s to position (p+1-n) + + For the position 3 + + We get:: + + ~(~0 << n) << (p+1 -n) = 0000 0111 << (3+1 -3) + = 0000 0111 << 1 + = 000 0111 0 + = 0000 1111 + +Inverting the bits can accomplished by the XOR operation ``(^)`` + +So, a value like 8 which is 0000 1000 can be inverted can inverted from 3rd +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 new file mode 100644 index 00000000..e0807a05 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.8_rightrot.rst @@ -0,0 +1,87 @@ +=================================================================================== +Exercise 2.8-returns the value of the integer x rotated to the right by n positions +=================================================================================== + +Question +======== + +Write a function rightrot(x,n) that returns the value of the integer x rotated +to the right by n positions. + +.. literalinclude:: cprogs/ex_2.8_rightrot.c + :language: c + +Explanation +=========== + +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. + +:: + + x = x >> 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). + +Visualization +============= + +.. raw:: html + + diff --git a/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst b/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst new file mode 100644 index 00000000..a556a6d6 --- /dev/null +++ b/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst @@ -0,0 +1,140 @@ +============================================= +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:: cprogs/ex_2.9_bitcount2s.c + :language: c + +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. + +Visualization +============= + +.. raw:: html + + diff --git a/source/cprogramming/chapter2/index.rst b/source/cprogramming/chapter2/index.rst new file mode 100644 index 00000000..ad4585bd --- /dev/null +++ b/source/cprogramming/chapter2/index.rst @@ -0,0 +1,17 @@ +========= +Chapter 2 +========= + +.. 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 diff --git a/source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c b/source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c new file mode 100644 index 00000000..1655f8ae --- /dev/null +++ b/source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c @@ -0,0 +1,31 @@ +#include + +int binsearch(int x, int v[], int n) { + int low, high, mid; + + low = 0; + high = n - 1; + + mid = (low + high) / 2; + + while (low < high && x != v[mid]) { + if (x > v[mid]) + low = mid + 1; + else + high = mid - 1; + + mid = (low + high) / 2; + } + + if (x == v[mid]) + return mid; + 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 new file mode 100644 index 00000000..d4d9bc8b --- /dev/null +++ b/source/cprogramming/chapter3/cprogs/ex_3.3_expand.c @@ -0,0 +1,42 @@ +#include +#define MAXLINE 100 + +void expand(char s1[], char s2[]) { + int i, j, c; + + i = j = 0; + + while ((c = s1[i++]) != '\0') + if (s1[i] == '-' && s1[i + 1] >= c) { + i++; + while (c < s1[i]) + s2[j++] = c++; + } else + s2[j++] = c; + + s2[j] = '\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 main(void) { + char s1[MAXLINE], s2[MAXLINE]; + + mgetline(s1, MAXLINE); + + expand(s1, s2); + + 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 new file mode 100644 index 00000000..e0e1e2bf --- /dev/null +++ b/source/cprogramming/chapter3/cprogs/ex_3.4_itoa-2.c @@ -0,0 +1,50 @@ +#include +#include + +#define MAXLINE 1000 + +#define abs(x) ((x) > 0 ? (x) : -(x)) + +void reverse(char s[]) { + int c, i, j; + + 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 i, sign; + + sign = n; + + i = 0; + + do { + s[i++] = abs(n % 10) + '0'; + + } while ((n /= 10) != 0); + + if (sign < 0) + s[i++] = '-'; + + s[i] = '\0'; + + reverse(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); + + 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 new file mode 100644 index 00000000..76a020d8 --- /dev/null +++ b/source/cprogramming/chapter3/cprogs/ex_3.5_itob.c @@ -0,0 +1,47 @@ +#include +#include + +#define MAXLINE 100 + +void reverse(char s[]) { + int i, j, c; + + 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) { + int i, j, sign; + + if ((sign = n) < 0) + n = -n; + + i = 0; + + do { + j = n % b; + + s[i++] = (j <= 9) ? j + '0' : j + 'a' - 10; + } while ((n /= b) > 0); + + if (sign < 0) + s[i++] = '-'; + + s[i] = '\0'; + + reverse(s); +} + +int main(void) { + int number, base; + char str[MAXLINE]; + + 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 new file mode 100644 index 00000000..1cb57850 --- /dev/null +++ b/source/cprogramming/chapter3/cprogs/ex_3.6_itoa-3.c @@ -0,0 +1,48 @@ +#include +#include + +#define MAXLIMIT 100 + +void reverse(char s[]) { + int i, j, c; + + 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) { + int i, sign; + + if ((sign = n) < 0) + n = -n; + i = 0; + + do { + s[i++] = (n % 10) + '0'; + + } while ((n /= 10) > 0); + + if (sign < 0) + s[i++] = '-'; + + while (i < w) + s[i++] = ' '; + + s[i] = '\0'; + + reverse(s); +} + +int main(void) { + int number, width; + char str[MAXLIMIT]; + + 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 new file mode 100644 index 00000000..912c5ebf --- /dev/null +++ b/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst @@ -0,0 +1,30 @@ +====================================================================== +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:: cprogs/ex_3.1_binsearch-2.c + :language: c + :tab-width: 4 + +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 diff --git a/source/cprogramming/chapter3/ex_3.2_escape.rst b/source/cprogramming/chapter3/ex_3.2_escape.rst new file mode 100644 index 00000000..5b862de8 --- /dev/null +++ b/source/cprogramming/chapter3/ex_3.2_escape.rst @@ -0,0 +1,28 @@ +======================================================== +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:: cprogs/ex_3.2_escape.c + :language: c + :tab-width: 4 + +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. diff --git a/source/cprogramming/chapter3/ex_3.3_expand.rst b/source/cprogramming/chapter3/ex_3.3_expand.rst new file mode 100644 index 00000000..56af6625 --- /dev/null +++ b/source/cprogramming/chapter3/ex_3.3_expand.rst @@ -0,0 +1,32 @@ +============================================================== +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:: cprogs/ex_3.3_expand.c + :language: c + :tab-width: 4 + + +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. diff --git a/source/cprogramming/chapter3/ex_3.4_itoa-2.rst b/source/cprogramming/chapter3/ex_3.4_itoa-2.rst new file mode 100644 index 00000000..510f7fac --- /dev/null +++ b/source/cprogramming/chapter3/ex_3.4_itoa-2.rst @@ -0,0 +1,31 @@ +====================================================== +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:: cprogs/ex_3.4_itoa-2.c + :language: c + :tab-width: 4 + +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`. diff --git a/source/cprogramming/chapter3/ex_3.5_itob.rst b/source/cprogramming/chapter3/ex_3.5_itob.rst new file mode 100644 index 00000000..bdecec35 --- /dev/null +++ b/source/cprogramming/chapter3/ex_3.5_itob.rst @@ -0,0 +1,31 @@ +============================================================== +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:: cprogs/ex_3.5_itob.c + :language: c + +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. + diff --git a/source/cprogramming/chapter3/ex_3.6_itoa-3.rst b/source/cprogramming/chapter3/ex_3.6_itoa-3.rst new file mode 100644 index 00000000..c67fe780 --- /dev/null +++ b/source/cprogramming/chapter3/ex_3.6_itoa-3.rst @@ -0,0 +1,42 @@ +==================================== +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:: cprogs/ex_3.6_itoa-3.c + :language: c + :tab-width: 4 + +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 + + \ No newline at end of file diff --git a/source/cprogramming/chapter3/index.rst b/source/cprogramming/chapter3/index.rst new file mode 100644 index 00000000..f0f239b7 --- /dev/null +++ b/source/cprogramming/chapter3/index.rst @@ -0,0 +1,13 @@ +========= +Chapter 3 +========= + +.. 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 diff --git a/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c b/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c new file mode 100644 index 00000000..482b0f4a --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c @@ -0,0 +1,139 @@ +/** + * 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/chapter4/cprogs/ex_4.11_getch_static.c b/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c new file mode 100644 index 00000000..5fd4166b --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c @@ -0,0 +1,126 @@ +/** + * 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(); +} \ 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 new file mode 100644 index 00000000..af061ab6 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c @@ -0,0 +1,41 @@ +/** + * 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'; + +} \ 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 new file mode 100644 index 00000000..6cb96c76 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c @@ -0,0 +1,57 @@ +/** + * a recursive version of reverse(s); the string reverse function + **/ + +#include +#include + +#define MAXLINE 100 + +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); + } 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 new file mode 100644 index 00000000..d993be5b --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c @@ -0,0 +1,17 @@ +/* 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); +} \ 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 new file mode 100644 index 00000000..297a4a7e --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c @@ -0,0 +1,34 @@ +/* strindex which returns rightmost occurrence */ + +#include + +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; +} + +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); + +} \ 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 new file mode 100644 index 00000000..75a8003f --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c @@ -0,0 +1,83 @@ +/** + * + * Program demonstrating atof(char s[]).The function which converts the string + * to a floating point value. + * + */ + +#include +#include + +#define MAXLINE 100 + +int power(int base, int exp) { + int power; + power = 1; + while (exp-- > 0) + power *= base; + + return power; +} + +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 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'; +} + +int main(void) { + char str[MAXLINE]; + double num; + mgetline(str, MAXLINE); + + num = myatof(str); + printf("%f", num); + + 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 new file mode 100644 index 00000000..8e861943 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c @@ -0,0 +1,126 @@ +/** + * 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 +#include +#include + +#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 */ + +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; +} + +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; + } +} + +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; +} + +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 new file mode 100644 index 00000000..b0befcd5 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c @@ -0,0 +1,149 @@ +#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 */ + +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; +} + +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 new file mode 100644 index 00000000..21c83a19 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c @@ -0,0 +1,193 @@ +/** + * compile with -lm flag(the static math library) + **/ + +#include +#include +#include +#include +#include + +#define MAXOP 100 +#define NUMBER '0' +#define NAME 'n' +#define BUFSIZE 100 +#define MAXVAL 100 + +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[]); + +/* 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; +} + +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 (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; +} + +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); +} \ 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 new file mode 100644 index 00000000..0f5e5516 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c @@ -0,0 +1,125 @@ +#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 getch(void); +void ungetch(int); + +/* 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; +} + +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; + } +} + +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; +} + +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/cprogs/ex_4.7_ungets.c b/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c new file mode 100644 index 00000000..168aac21 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c @@ -0,0 +1,66 @@ +/** + * 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/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 new file mode 100644 index 00000000..d72b8e2a --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c @@ -0,0 +1,46 @@ +/** + * 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/chapter4/ex_4.10_calculator_getline.rst b/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst new file mode 100644 index 00000000..128231ff --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst @@ -0,0 +1,90 @@ +======================================== +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:: cprogs/ex_4.10_calculator_getline.c + :language: c + +Explanation +=========== + +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. + + +:: + + /* getop: get next operator or numeric operand */ + + int getop(char s[]) + { + int c,i; + + if(line[li] == '\0') + if(_getline(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 _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 +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 + +Visualize It +============ + +* https://pythontutor.com/c.html + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.11_getch_static.rst b/source/cprogramming/chapter4/ex_4.11_getch_static.rst new file mode 100644 index 00000000..140f0bfc --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.11_getch_static.rst @@ -0,0 +1,90 @@ +==================================== +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:: cprogs/ex_4.11_getch_static.c + :language: c + +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 + +Visualize It +============ + +* https://pythontutor.com/c.html + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.12_recursive_itoa.rst b/source/cprogramming/chapter4/ex_4.12_recursive_itoa.rst new file mode 100644 index 00000000..906bd6c7 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.12_recursive_itoa.rst @@ -0,0 +1,66 @@ +======================================================================== +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:: cprogs/ex_4.12_recursive_itoa.c + :language: c + :tab-width: 4 + +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. + +Visualize It +============ + +.. raw:: html + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.13_reverse_string.rst b/source/cprogramming/chapter4/ex_4.13_reverse_string.rst new file mode 100644 index 00000000..683ae004 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.13_reverse_string.rst @@ -0,0 +1,60 @@ +==================================== +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:: cprogs/ex_4.13_reverse_string.c + :language: c + + +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`. + +Visualize It +============ + +.. raw:: html + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.14_swap_t_x_y.rst b/source/cprogramming/chapter4/ex_4.14_swap_t_x_y.rst new file mode 100644 index 00000000..a55f1978 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.14_swap_t_x_y.rst @@ -0,0 +1,45 @@ +============================================================== +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:: cprogs/ex_4.14_swap_t_x_y.c + :language: c + +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`. + +Visualize It +============ + +.. raw:: html + + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.1_strindex_rightmost.rst b/source/cprogramming/chapter4/ex_4.1_strindex_rightmost.rst new file mode 100644 index 00000000..e24b2645 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.1_strindex_rightmost.rst @@ -0,0 +1,56 @@ +======================================================== +Exercise 4.1- strindex which returns rightmost occurance +======================================================== + +Code +==== + +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:: cprogs/ex_4.1_strindex_rightmost.c + :language: c + +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. + + +Visualize It +============ + +.. raw:: html + + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.2_atof_scientific.rst b/source/cprogramming/chapter4/ex_4.2_atof_scientific.rst new file mode 100644 index 00000000..c6c91756 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.2_atof_scientific.rst @@ -0,0 +1,41 @@ +======================================================== +Exercise 4.2 - Extend atof to handle scientific notation +======================================================== + +Question +======== + +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. + + +.. literalinclude:: cprogs/ex_4.2_atof_scientific.c + :language: c + +Explanation +=========== + +For the input:: + + 1.0e10 + +We might get the output:: + + 1410065408.000000 + +Visualize It +============ + +.. raw:: html + + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.3_rpn_modulus_negative.rst b/source/cprogramming/chapter4/ex_4.3_rpn_modulus_negative.rst new file mode 100644 index 00000000..0180b4ca --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.3_rpn_modulus_negative.rst @@ -0,0 +1,65 @@ +======================================================== +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:: cprogs/ex_4.3_rpn_modulus_negative.c + :language: c + +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 + +Visualize It +============ + +.. raw:: html + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.4_rpn_top_two_elements.rst b/source/cprogramming/chapter4/ex_4.4_rpn_top_two_elements.rst new file mode 100644 index 00000000..f67ad7f7 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.4_rpn_top_two_elements.rst @@ -0,0 +1,74 @@ +=================================================================================== +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:: cprogs/ex_4.4_rpn_top_two_elements.c + :language: c + +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`. + +Visualize It +============ + +* https://pythontutor.com + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.5_calculator_math_functions.rst b/source/cprogramming/chapter4/ex_4.5_calculator_math_functions.rst new file mode 100644 index 00000000..936c1ea2 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.5_calculator_math_functions.rst @@ -0,0 +1,58 @@ +========================================================= +Exercise 4.5 - RPN Calculator with mathematical functions +========================================================= + +Question +======== + +Add access to library functions like sin, exp, and pow. + +.. literalinclude:: cprogs/ex_4.5_calculator_math_functions.c + :language: c + + +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); + } + +Visualize It +============ + +* https://pythontutor.com + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.6_calculator_variables.rst b/source/cprogramming/chapter4/ex_4.6_calculator_variables.rst new file mode 100644 index 00000000..e1515d27 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.6_calculator_variables.rst @@ -0,0 +1,47 @@ +============================================ +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:: cprogs/ex_4.6_calculator_variables.c + :language: c + + +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. + +Visualize It +============ + +* https://pythontutor.com/ + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.7_ungets.rst b/source/cprogramming/chapter4/ex_4.7_ungets.rst new file mode 100644 index 00000000..ff592b53 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.7_ungets.rst @@ -0,0 +1,50 @@ +================================================================================== +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:: cprogs/ex_4.7_ungets.c + :language: c + +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. + +Visualize It +============ + +.. raw:: html + + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.8_getch_ungetch_pushback.rst b/source/cprogramming/chapter4/ex_4.8_getch_ungetch_pushback.rst new file mode 100644 index 00000000..4b9f3859 --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.8_getch_ungetch_pushback.rst @@ -0,0 +1,38 @@ +============================================================ +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:: cprogs/ex_4.8_getch_ungetch_pushback.c + :language: c + + +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. + + +Visualize It +============ + +.. raw:: html + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst b/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst new file mode 100644 index 00000000..14f507ba --- /dev/null +++ b/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst @@ -0,0 +1,39 @@ +======================================================= +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:: cprogs/ex_4.9_getch_ungetch_eof.c + :language: c + +Explanation +=========== + +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 +buf[BUFSIZE]` and `ungetch(c)` will store the character c, including EOF, now in +an integer array. + +Visualize It +============ + +.. raw:: html + + + + +Try It +====== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter4/index.rst b/source/cprogramming/chapter4/index.rst new file mode 100644 index 00000000..9d7c2c94 --- /dev/null +++ b/source/cprogramming/chapter4/index.rst @@ -0,0 +1,22 @@ +========= +Chapter 4 +========= + +.. toctree:: + :maxdepth: 1 + + ex_4.1_strindex_rightmost + ex_4.2_atof_scientific + 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 + 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/ex_5.10_exprcmd.rst b/source/cprogramming/chapter5/ex_5.10_exprcmd.rst new file mode 100644 index 00000000..6c9f667f --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.10_exprcmd.rst @@ -0,0 +1,34 @@ +==================================================== +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:: cprogs/ex_5.10_exprcmd.c + :language: c + :tab-width: 4 + +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. + + + + diff --git a/source/cprogramming/chapter5/ex_5.11_conddetab.rst b/source/cprogramming/chapter5/ex_5.11_conddetab.rst new file mode 100644 index 00000000..07d2d378 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.11_conddetab.rst @@ -0,0 +1,37 @@ +======================================================= +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:: cprogs/ex_5.11_conddetab.c + :language: c + :tab-width: 4 + +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. + diff --git a/source/cprogramming/chapter5/ex_5.12_condientab.rst b/source/cprogramming/chapter5/ex_5.12_condientab.rst new file mode 100644 index 00000000..bde5a5d6 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.12_condientab.rst @@ -0,0 +1,57 @@ +================================================== +Exercise 5.12 - entab -m + which accepts arguments +================================================== + +Question +======== + +Extend entab and detab to accept the shorthand. + +.. literalinclude:: cprogs/ex_5.12_condientab.c + :language: c + :tab-width: 4 + + +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. + + + + diff --git a/source/cprogramming/chapter5/ex_5.13_tailn.rst b/source/cprogramming/chapter5/ex_5.13_tailn.rst new file mode 100644 index 00000000..d837d56b --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.13_tailn.rst @@ -0,0 +1,47 @@ +===================================================== +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:: cprogs/ex_5.13_tailn.c + :language: c + :tab-width: 4 + + +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 `_getline(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. + + + + + diff --git a/source/cprogramming/chapter5/ex_5.14_sortrevnum.rst b/source/cprogramming/chapter5/ex_5.14_sortrevnum.rst new file mode 100644 index 00000000..1de55ca0 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.14_sortrevnum.rst @@ -0,0 +1,109 @@ +===================================================== +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:: cprogs/ex_5.14_sortrevnum.c + :language: c + :tab-width: 4 + +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. + + + + + diff --git a/source/cprogramming/chapter5/ex_5.15_sortfnr.rst b/source/cprogramming/chapter5/ex_5.15_sortfnr.rst new file mode 100644 index 00000000..368b5a4c --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.15_sortfnr.rst @@ -0,0 +1,36 @@ +================================================== +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:: cprogs/ex_5.15_sortfnr.c + :language: c + :tab-width: 4 + + +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 + + + + + + diff --git a/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst b/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst new file mode 100644 index 00000000..0918ede2 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst @@ -0,0 +1,55 @@ +=============================================================== +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:: cprogs/ex_5.16_sort_dfnr.c + :language: c + :tab-width: 4 + + +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 + + + diff --git a/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst b/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst new file mode 100644 index 00000000..67c15c01 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst @@ -0,0 +1,69 @@ +==================================== +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:: cprogs/ex_5.17_sortdfnr-withoption.c + :language: c + :tab-width: 4 + +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" + + +:: + + -n +2: This specifies the second field to sort by + +* -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 new file mode 100644 index 00000000..ac8273d0 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst @@ -0,0 +1,29 @@ +========================================= +Exercise 5.18 - recover from input errors +========================================= + +Question +======== + +Make dcl recover from input errors. + +.. literalinclude:: cprogs/ex_5.18_dcl-errorec.c + :language: c + :tab-width: 4 + +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 + + +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. + diff --git a/source/cprogramming/chapter5/ex_5.19_undcl.rst b/source/cprogramming/chapter5/ex_5.19_undcl.rst new file mode 100644 index 00000000..ba9f9e94 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.19_undcl.rst @@ -0,0 +1,58 @@ +======================================================== +Exercise 5.19 - undcl does not add redundant parentheses +======================================================== + +Question +======== + +Modify undcl so that it does not add redundant parentheses to declarations. + +.. literalinclude:: cprogs/ex_5.19_undcl.c + :language: c + :tab-width: 4 + + +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) { + + diff --git a/source/cprogramming/chapter5/ex_5.1_getint.rst b/source/cprogramming/chapter5/ex_5.1_getint.rst new file mode 100644 index 00000000..7de50d3f --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.1_getint.rst @@ -0,0 +1,80 @@ +================================================== +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:: cprogs/ex_5.1_getint.c + :language: c + :tab-width: 4 + + +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. + + + + diff --git a/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst b/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst new file mode 100644 index 00000000..a18df686 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst @@ -0,0 +1,56 @@ +================================================================================== +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. + +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 + + +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 + + diff --git a/source/cprogramming/chapter5/ex_5.2_getfloat.rst b/source/cprogramming/chapter5/ex_5.2_getfloat.rst new file mode 100644 index 00000000..0c34df82 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.2_getfloat.rst @@ -0,0 +1,60 @@ +================================================ +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:: cprogs/ex_5.2_getfloat.c + :language: c + :tab-width: 4 + +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. + + + + diff --git a/source/cprogramming/chapter5/ex_5.3_strcat.rst b/source/cprogramming/chapter5/ex_5.3_strcat.rst new file mode 100644 index 00000000..bc411417 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.3_strcat.rst @@ -0,0 +1,49 @@ +============================================================== +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:: cprogs/ex_5.3_strcat.c + :language: c + :tab-width: 4 + + +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`. + + + + diff --git a/source/cprogramming/chapter5/ex_5.4_strend.rst b/source/cprogramming/chapter5/ex_5.4_strend.rst new file mode 100644 index 00000000..29ea502d --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.4_strend.rst @@ -0,0 +1,78 @@ +============================================================================= +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:: cprogs/ex_5.4_strend.c + :language: c + :tab-width: 4 + +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. + + + + diff --git a/source/cprogramming/chapter5/ex_5.5_strncpy.rst b/source/cprogramming/chapter5/ex_5.5_strncpy.rst new file mode 100644 index 00000000..bd40882b --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.5_strncpy.rst @@ -0,0 +1,46 @@ +=============================================================== +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:: cprogs/ex_5.5_strncpy.c + :language: c + :tab-width: 4 + + +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. + + + + + diff --git a/source/cprogramming/chapter5/ex_5.6_findpattern.rst b/source/cprogramming/chapter5/ex_5.6_findpattern.rst new file mode 100644 index 00000000..8ebf58e8 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.6_findpattern.rst @@ -0,0 +1,75 @@ +============================================== +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:: cprogs/ex_5.6_findpattern.c + :language: c + :tab-width: 4 + +Explanation +=========== + +_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. _getline 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. + + + + + diff --git a/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst b/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst new file mode 100644 index 00000000..e3a299da --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst @@ -0,0 +1,43 @@ +==================================== +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:: cprogs/ex_5.7_readlines_using_array.c + :language: c + :tab-width: 4 + +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. + +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. + + + + + diff --git a/source/cprogramming/chapter5/ex_5.8_day_date.rst b/source/cprogramming/chapter5/ex_5.8_day_date.rst new file mode 100644 index 00000000..ff249bd3 --- /dev/null +++ b/source/cprogramming/chapter5/ex_5.8_day_date.rst @@ -0,0 +1,37 @@ +============================================================== +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:: cprogs/ex_5.8_day_date.c + :language: c + :tab-width: 4 + +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. + + + + 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 new file mode 100644 index 00000000..90442886 --- /dev/null +++ b/source/cprogramming/chapter6/cprogs/ex_6.1_getword.c @@ -0,0 +1,111 @@ +#include +#include +#include + +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}; + +int mygetword(char *, int); + +int binsearch(char *, struct key *, int); + +#define NKEYS (sizeof(keytab) / sizeof(keytab[0])) +#define MAXWORD 100 + +int main(int argc, char *argv[]) { + int n; + char word[MAXWORD]; + + while (mygetword(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); +} + +int binsearch(char *word, struct key lkeytab[], int n) { + int cond; + int low, high, mid; + + low = 0; + high = n - 1; + while (low <= high) { + mid = (low + high) / 2; + if ((cond = strcmp(word, lkeytab[mid].word)) < 0) + high = mid - 1; + else if (cond > 0) + low = mid + 1; + else + return mid; + } + return -1; +} + +int mygetword(char *word, int lim) { + int c, getch(void); + void ungetch(int); + char *w = word; + int t; + + while (isspace(c = getch())); + if (c != EOF) + *w++ = c; + if (!isalpha(c)) { + if (c == '\"') { /*string constant*/ + for (c = getch(); c != '\"'; c = getch()); + } else if (c == '#') { /*preprocessor*/ + for (c = getch(); c != '\n'; c = getch()); + } else if (c == '/') /*comment*/ + if ((c = getch()) == '/') { /*single comment*/ + for (c = getch(); c != '\n'; c = getch()); + } else if (c == '*') { /*mutiline comment*/ + for (c = getch(), t = getch(); c != '*' && t != '/'; + c = getch(), t = getch()) + ungetch(t); + } else + ungetch(c); + else /*underscore*/ + for (; !isspace(c) && c != EOF; c = getch()); + if (c != '\"' && c != '\n' && c != '/') + ungetch(c); + *w = '\0'; + return c; + } + + for (; --lim > 0; w++) + if (!isalnum(*w = getch())) { + if (!isspace(*w)) { + ungetch(*w); + return (*w); + } else { + ungetch(*w); + break; + } + } + *w = '\0'; + return word[0]; +} + +#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/chapter6/cprogs/ex_6.2_identical_variables.c b/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c new file mode 100644 index 00000000..f9c15f40 --- /dev/null +++ b/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c @@ -0,0 +1,385 @@ +/* + * Exercise 6-2 in K&R2 on page 143. Original By: Barrett Drawdy + * 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. + */ + +#include +#include +#include +#include + +#define MAXWORD 1000 /* longest word that can be read by getword */ +#define DEFAULT_COMP_LEN 6 /* default length to compare */ + +/* + * tnode: Tree node from K&R2 page 140. Words are initially read into + * the tree by getword. + */ +struct tnode { + char *word; + int count; + struct tnode *left; + struct tnode *right; +}; + +/* + * 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 */ + struct simword *nextword; /* next node */ +}; + +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[]) { + struct tnode *root; + char word[MAXWORD]; + struct simroot *listroot; + int len; + + /* get all the words */ + root = NULL; + while (mgetword(word, MAXWORD) != 'x') + if (isalpha(word[0])) + root = addtree(root, word); + + if (argc == 1) + len = DEFAULT_COMP_LEN; + else if (argc == 2) + len = atoi(argv[1]); + else { + printf("Incorrect number of arguments.\n"); + return 1; + } + + /* parse the tree to find similar words and populate list */ + listroot = NULL; + listroot = parse(root, len); + treeprint(root); /* prints all the words */ + printf("\nDuplicate list:\n\n"); + printlist(listroot, len); /* prints the similar words */ + + return 0; +} /* end of main() */ + +/* + * parse: Reads the tree created by getword. It finds words that are + * similar in the first len letters and places them in the list structure + * that it creates. + */ +struct simroot *parse(struct tnode *node, int len) { + struct tnode *temp; /* pointer to the children of the node */ + int this_len; /* length of the word in the current node */ + static struct simroot *root = NULL; /* points to the root of the tree */ + + if (node == NULL) + return NULL; + + this_len = strlen(node->word); + + parse(node->left, len); /* start in the left subtree */ + + temp = node->left; /* find the closest left child and compare */ + if (temp != NULL) { + while (temp->right != NULL) + temp = temp->right; + /* if the word matches, put both words in the list */ + if (this_len >= len && strncmp(temp->word, node->word, len) == 0) { + root = addroot(root, temp, len); + addroot(root, node, len); + } + } + + temp = node->right; /* find the closest right child and compare */ + if (temp != NULL) { + while (temp->left != NULL) + temp = temp->left; + /* if the word matches, put both words in the list */ + if (this_len >= len && strncmp(temp->word, node->word, len) == 0) { + root = addroot(root, node, len); + addroot(root, temp, len); + } + } + + parse(node->right, len); /* continue on to right subtree */ + + return root; +} + +/* + * printlist: Prints the roots that were similar, followed by the list + * of words. + */ +void printlist(struct simroot *p, int len) { + int i; + if (p == NULL) + return; + for (i = 0; i < len; ++i) /* print the root */ + putchar(p->firstword->word[i]); + putchar('\n'); + printwords(p->firstword); /* print the list of words */ + printlist(p->nextroot, len); /* print the next root/list */ +} + +/* + * printword: Prints the list of words with the same roots. + */ +void printwords(struct simword *p) { + printf(" %4d %s\n", p->count, p->word); + if (p->nextword != NULL) + printwords(p->nextword); +} + +struct tnode *talloc(void); + +char *mstrdup(char *); + +struct simword *walloc(struct simword *, struct tnode *); + +void addword(struct simword *, struct tnode *); + +/* + * addroot: When a node n is passed to addroot, n->word is compared to the + * first word in ps list. If they have are the same for the first 'len' + * characters, then the word is added to that list. Otherwise, it is passed + * along the simroots until it reaches the end, where a new simroot is + * created if the word has a new root. + */ +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->nextroot = NULL; + p->firstword = walloc(p->firstword, n); + } + /* 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 */ + else + p->nextroot = addroot(p->nextroot, n, len); + return p; +} + +/* + * addword: Compares the word from n to the word in p. If they are the same, + * the word was already added and it returns. This continues down the list + * until the end, where a new node is created if the word is new. + */ +void addword(struct simword *p, struct tnode *n) { + /* word was already added */ + if (strcmp(p->word, n->word) == 0) + return; + /* end of list. create a new node */ + if (p->nextword == NULL) + p->nextword = walloc(p->nextword, n); + /* 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)); + if (p != NULL) { + p->word = n->word; + p->count = n->count; + p->nextword = NULL; + } + return p; +} + +/* mgetword from Ex6.1 */ + +#define IN 1 +#define OUT 0 + +int mgetword(char *word, int lim) { + int c, d, getch(void), comment, string, directive; + void ungetch(int); + char *w = word; + + comment = string = directive = OUT; + + while (isspace(c = getch())); + + /* Check if inside a comment */ + + if (c == '/') { + if ((d = getch()) == '*') { + comment = IN; + } else { + comment = OUT; + ungetch(d); + } + } + + /* Check if inside a quote */ + + if (c == '\"') { + string = IN; + } + + /* Check if inside a directive */ + + if (c == '#') { + directive = IN; + } + + if (c == '\\') { + c = getch(); /* ignore the \\ character */ + } + + if (comment == OUT && string == OUT && directive == OUT) { + + if (c != EOF) + *w++ = c; + + if (!isalnum(c) && c != '_') { + *w = '\0'; + return c; + } + + for (; --lim > 0; w++) { + *w = getch(); + if (!isalnum(*w) && *w != '_') { + ungetch(*w); + break; + } + } + *w = '\0'; + return word[0]; + } else if (comment == IN) { + *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; + *w = '\0'; + } + + return c; +} + +/*************************************************************************** + * 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 cond; + + if (p == NULL) { /* new word */ + p = talloc(); + p->word = mstrdup(w); + p->count = 1; + p->left = p->right = NULL; + } else if ((cond = strcmp(w, p->word)) == 0) + p->count++; + else if (cond < 0) + p->left = addtree(p->left, w); + else + p->right = addtree(p->right, w); + return p; +} + +/* treeprint: From K&R2 page 142. Prints tree p in-order. */ +void treeprint(const struct tnode *p) { + if (p != NULL) { + treeprint(p->left); + printf("%4d %s\n", p->count, p->word); + treeprint(p->right); + } +} + +/* talloc: From K&R2 page 142. Makes a tnode. */ +struct tnode *talloc(void) { + 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); + 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(); +} + +void ungetch(int c) { /* push character back on input */ + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; + return; +} diff --git a/source/cprogramming/chapter6/cprogs/ex_6.3.c b/source/cprogramming/chapter6/cprogs/ex_6.3.c new file mode 100644 index 00000000..a2c3b391 --- /dev/null +++ b/source/cprogramming/chapter6/cprogs/ex_6.3.c @@ -0,0 +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. +* +*/ + +/* + * 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 + +#define MAXWORD 500 + +struct tnode{ + char *word; + unsigned int count; + struct ocurLine *lineOfOccurence; + + struct tnode *left; + struct tnode *right; +}; + + +struct ocurLine{ + unsigned int line; + struct ocurLine *next; +}; + +int binarySearch(const char *arr[], int l, int r, char *x); + +void treeprint(const struct tnode *p); +char *mstrdup(char *s); + +int getWord(char *word, int lim); + +void ungetch(char c); +int getch(void); + +char buf; /* buffer for getch/ungetch */ + +struct tnode *talloc(void); +struct tnode *addtree(struct tnode *p, char *w, unsigned int l); + +void printline(const struct ocurLine *p); + +struct ocurLine *linealloc(void); +struct ocurLine *addLine(struct ocurLine *p, unsigned int l); + +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); +} + + +/* 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 (cmp == 0) + return mid; + + if (cmp > 0) + return binarySearch(arr, l, mid - 1, x); + + return binarySearch(arr, mid + 1, r, x); + } + + return -1; +} + + +int getWord(char *word, int lim) +{ + int c; + + char *w = word; + + while (isspace(c = getch()) && c != '\n') + ; + + if (c != EOF) + *w++ = c; + + if (!isalpha(c) && c != '_' && c != '#') { + *w = '\0'; + return c; + } + + for ( ; --lim > 0; w++) + if (!isalnum(*w = getch())){ + ungetch(*w); + break; + } + + *w = '\0'; + return word[0]; +} + +/* 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->count = 1; + 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->lineOfOccurence = addLine(p->lineOfOccurence, l); + } + else if(cond < 0) + p->left = addtree(p->left, w, l); + else + p->right = addtree(p->right, w, l); + return p; +} + +/* treeprint: prints all the branches of the tree with words.*/ +void treeprint(const struct tnode *p) +{ + + if(p != NULL) { + treeprint(p->left); + + printf("%s: [", p->word); + + printline(p->lineOfOccurence); + + printf("]\n"); + + treeprint(p->right); + } +} + +/* talloc: From K&R2 page 142. Makes a tnode. */ +struct tnode *talloc(void) +{ + return (struct tnode *) malloc(sizeof(struct tnode)); +} + + +/* 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); + } +} + +/* 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; +} + +/* 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 *p; + + p = (char *) malloc(strlen(s) + 1); + + if(p != NULL) + strcpy(p, s); + return p; +} + +/************************************************************* + * 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(); +} + +/* 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 new file mode 100644 index 00000000..af21156b --- /dev/null +++ b/source/cprogramming/chapter6/cprogs/ex_6.4.c @@ -0,0 +1,209 @@ +/* + * 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. + */ + +/* + * Create 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. + */ + +#include +#include +#include +#include + +#define MAXWORD 1000 + +struct tnode { + char *word; + int count; + struct tnode *left; + struct tnode *right; +}; + +struct bynumbernode { + int number; + struct words *wordlist; + struct bynumbernode *left; + struct bynumbernode *right; +}; + +struct words { + char *word; + struct words *nextword; +}; + +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)); +}; + +struct bynumbernode *bynumbernodealloc(void) { + return (struct bynumbernode *) malloc(sizeof(struct bynumbernode)); +}; + +struct words *wordsalloc(void) { + return (struct words *) malloc(sizeof(struct words)); +}; + +#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; + return; +} + +char *mstrdup(char *s) { + char *p; + p = (char *) malloc(strlen(s) + 1); + if (p != NULL) { + strcpy(p, s); + } + return p; +} + +int getword(char *word, int lim) { + int c, getch(void); + void ungetch(int); + char *w = word; + + while (isspace(c = getch()) || c == '_' || c == '/' || c == '#' || + c == '*' || c == '"'); + + if (c != EOF) { + *w++ = c; + } + if (!isalpha(c)) { + *w = '\0'; + return c; + } + for (; --lim > 0; w++) { + if (!isalnum(*w = getch())) { + ungetch(*w); + break; + } + } + *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; + + if (p == NULL) { /* new word */ + p = talloc(); // make new node + p->word = mstrdup(w); + p->count = 1; + p->left = p->right = NULL; + } else if ((cond = strcmp(w, p->word)) == 0) { + p->count++; + } else if (cond < 0) { + p->left = addtree(p->left, w); + } else { + p->right = addtree(p->right, w); + } + return p; +} + +// treeprint: in-order print of tree p +void treeprint(const struct bynumbernode *p) { + if (p != NULL) { + treeprint(p->left); + printwords(p->wordlist, p->number); + treeprint(p->right); + } +} + +void printwords(const struct words *w, const int count) { + if (w != NULL) { + printf("%d->%s", count, w->word); + w = w->nextword; + } + while (w != NULL) { + printf(", %s", w->word); + w = w->nextword; + } + printf("\n"); +} + +struct words *addwordtolist(struct words *list, char *w) { + if (list == NULL) { + list = wordsalloc(); + list->word = mstrdup(w); + list->nextword = NULL; + } else { + list->nextword = addwordtolist(list->nextword, w); + } + return list; +} + +struct bynumbernode *addnumtree(struct bynumbernode *n, int i, char *w) { + if (n == NULL) { + n = bynumbernodealloc(); + n->number = i; + n->wordlist = NULL; + n->wordlist = addwordtolist(n->wordlist, w); + } else if (n->number == i) { + addwordtolist(n->wordlist, w); + } else if (n->number < i) { + n->left = addnumtree(n->left, i, w); + } else { + n->right = addnumtree(n->right, i, w); + } + return n; +} + +struct bynumbernode *traverse(const struct tnode *p, struct bynumbernode *q) { + if (p != NULL) { + q = traverse(p->left, q); + q = addnumtree(q, p->count, p->word); + q = traverse(p->right, q); + } + return q; +} + +void main() { + struct tnode *root; + char word[MAXWORD]; + + struct bynumbernode *nroot; + + root = NULL; + nroot = NULL; + while (getword(word, MAXWORD) != EOF) { + if (isalpha(word[0])) { + root = addtree(root, word); + } + } + + nroot = traverse(root, nroot); + + printf("Words by frequency:\n"); + + treeprint(nroot); + return; +} diff --git a/source/cprogramming/chapter6/cprogs/ex_6.5.c b/source/cprogramming/chapter6/cprogs/ex_6.5.c new file mode 100644 index 00000000..7dc6eec4 --- /dev/null +++ b/source/cprogramming/chapter6/cprogs/ex_6.5.c @@ -0,0 +1,114 @@ +/* Write a function undef that will remove a name and definition + * from the table maintained by lookup and install. + */ + +#include +#include +#include + +#define HASHSIZE 101 + +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 */ +}; + +/* hash: form hash value for string s */ +unsigned hash(char *s) { + unsigned hashval; + + for (hashval = 0; *s != '\0'; s++) + hashval = *s + 31 * hashval; + + return hashval % HASHSIZE; +} + +/* lookup: look for s in hashtab */ +struct nlist *lookup(char *s) { + struct nlist *np; + + for (np = hashtab[hash(s)]; np != NULL; np = np->next) + if (strcmp(s, np->name) == 0) + return np; /* found */ + return NULL; /* not found */ +} + +/* 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)); + + if (np == NULL || (np->name = strdup(name)) == NULL) + return NULL; + hashval = hash(name); + np->next = hashtab[hashval]; + hashtab[hashval] = np; + } else /* already there */ + free((void *) np->defn); /* free the previous defn */ + + if ((np->defn = strdup(defn)) == NULL) + return NULL; + + 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; + + found = lookup(name); + + if (found == NULL) /* not found and nothing to do */ + return NULL; + else { + if (found->next != NULL) { + found->next = found->next->next; + found = found->next; + } else { + hashtab[hash(name)] = NULL; + free((void *) found); + } + } + return found; +} + +int main(int argc, char *argv[]) { + struct nlist *table[4] = { + (install("key", "value")), + (install("key1", "value1")), + (install("key2", "value2")), + (install("key3", "value3"))}; + + int i; + + for (i = 0; i < 4; i++) { + printf("%s->%s\n", table[i]->name, table[i]->defn); + } + + undef("key"); + undef("key3"); + + struct nlist *result; + + char *keys[4] = {"key", "key1", "key2", "key3"}; + + for (i = 0; i < 4; i++) { + if ((result = lookup(keys[i])) == NULL) { + printf("key not found\n"); + } else { + printf("%s->%s\n", result->name, result->defn); + } + } + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter6/cprogs/ex_6.6.c b/source/cprogramming/chapter6/cprogs/ex_6.6.c new file mode 100644 index 00000000..a2296996 --- /dev/null +++ b/source/cprogramming/chapter6/cprogs/ex_6.6.c @@ -0,0 +1,215 @@ +#include +#include +#include +#include + +#define BUFSIZE 100 +#define MAXWORD 1000 +#define IN 1 +#define OUT 0 +#define HASHSIZE 101 + + +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 */ +}; + + +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) { + unsigned hashval; + + for (hashval = 0; *s != '\0'; s++) + hashval = *s + 31 * hashval; + + return hashval % HASHSIZE; +} + +/* lookup: look for s in hashtab */ +struct nlist *lookup(char *s) { + struct nlist *np; + + for (np = hashtab[hash(s)]; np != NULL; np = np->next) + if (strcmp(s, np->name) == 0) + return np; /* found */ + return NULL; /* not found */ +} + +/* 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)); + + if (np == NULL || (np->name = strdup(name)) == NULL) + return NULL; + hashval = hash(name); + np->next = hashtab[hashval]; + hashtab[hashval] = np; + } else /* already there */ + free((void *)np->defn); /* free the previous defn */ + + if ((np->defn = strdup(defn)) == NULL) + return NULL; + + return np; +} + +struct nlist *undef(char *name) { + struct nlist *found; + + found = lookup(name); + + if (found == NULL) /* not found and nothing to do */ + return NULL; + else { + if (found->next != NULL) { + found->next = found->next->next; + found = found->next; + } else { + hashtab[hash(name)] = NULL; + free((void *)found); + } + } + return found; +} + +int mgetword(char *word, int lim, int *lineno_addr) { + int c, d, getch(void), comment, string, directive; + void ungetch(int); + char *w = word; + + comment = string = directive = OUT; + + while (isspace(c = getch())) { + if (c == '\n') { + + *lineno_addr = *lineno_addr + 1; + } + } + /* Check if inside a comment */ + if (c == '/') { + if ((d = getch()) == '*') { + comment = IN; + } else { + comment = OUT; + ungetch(d); + } + } + + /* Check if inside a quote */ + if (c == '\"') { + string = IN; + } + + /* Check if inside a directive */ + if (c == '#') { + directive = IN; + } + + if (c == '\\') { + c = getch(); /* ignore the \\ character */ + } + + if (comment == OUT && string == OUT && directive == OUT) { + + if (c != EOF) + *w++ = c; + + if (!isalnum(c) && c != '_') { + *w = '\0'; + return c; + } + + for (; --lim > 0; w++) { + *w = getch(); + if (!isalnum(*w) && *w != '_') { + ungetch(*w); + break; + } + } + *w = '\0'; + return word[0]; + } else if (comment == IN) { + *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()) != ' ') { + if (c == '\\') { /* Take care of continuation line escape */ + *w++ = getch(); + } + } + + directive = OUT; + *w = '\0'; + } + + return c; +} + +int main(void) { + + int lineno = 0; + char word[MAXWORD]; + + char key[MAXWORD], value[MAXWORD]; + + 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 new file mode 100644 index 00000000..f601a78d --- /dev/null +++ b/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c @@ -0,0 +1,100 @@ +#include +#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, +}; + +int binsearch(char *, struct key *, int); +int getch(void); +int mgetword(char *, int); +void ungetch(int c); + +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; +} + +/* binsearch: find word in tab[0]...tab[n-1] */ +int binsearch(char *word, struct key tab[], int n) { + int cond; + int low, high, mid; + low = 0; + high = n - 1; + while (low <= high) { + mid = (low + high) / 2; + if ((cond = strcmp(word, tab[mid].word)) < 0) + high = mid - 1; + else if (cond > 0) + low = mid + 1; + else + return mid; + } + return -1; +} + +/* getword: get next word or character from input */ +int mgetword(char *word, int lim) { + int c; + char *w = word; + while (isspace(c = getch())); + if (c != EOF) + *w++ = c; + if (!isalpha(c)) { + *w = '\0'; + return c; + } + for (; --lim > 0; w++) + if (!isalnum(*w = getch())) { + ungetch(*w); + break; + } + *w = '\0'; + return word[0]; +} + +/* count C keywords */ +int main(int argc, char *argv[]) { + int n; + char word[MAXWORD]; + + 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 new file mode 100644 index 00000000..66111e33 --- /dev/null +++ b/source/cprogramming/chapter6/ex_6.1_getword.rst @@ -0,0 +1,32 @@ +====================== +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:: cprogs/ex_6.1_getword.c + :language: c + :tab-width: 4 + +This is program from Section 6.3 implementing getword. + +.. literalinclude:: cprogs/sec_6.3_getword.c + :language: c + :tab-width: 4 + +Explanation +=========== + +This program identifies the keywords in the given input. + +:: + + $ ./ex_6.1_getword + this is a short sentence. + 1 short + + diff --git a/source/cprogramming/chapter6/ex_6.2_identical_variables.rst b/source/cprogramming/chapter6/ex_6.2_identical_variables.rst new file mode 100644 index 00000000..6f9dd1cc --- /dev/null +++ b/source/cprogramming/chapter6/ex_6.2_identical_variables.rst @@ -0,0 +1,25 @@ +================================== +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:: cprogs/ex_6.2_identical_variables.c + :language: c + :tab-width: 4 + +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. + + diff --git a/source/cprogramming/chapter6/ex_6.3.rst b/source/cprogramming/chapter6/ex_6.3.rst new file mode 100644 index 00000000..b8aa9bec --- /dev/null +++ b/source/cprogramming/chapter6/ex_6.3.rst @@ -0,0 +1,52 @@ +=============================== +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:: cprogs/ex_6.3.c + :language: c + :tab-width: 4 + +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. + +:: + + [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 new file mode 100644 index 00000000..1f47fd45 --- /dev/null +++ b/source/cprogramming/chapter6/ex_6.4.rst @@ -0,0 +1,43 @@ +================================== +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:: cprogs/ex_6.4.c + :language: c + :tab-width: 4 + +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 + ab + bc + cd + ef + gh + ab + x + Words and their frequencies: + bc->1 + cd->1 + ef->1 + gh->1 + ab->3 + + + + diff --git a/source/cprogramming/chapter6/ex_6.5.rst b/source/cprogramming/chapter6/ex_6.5.rst new file mode 100644 index 00000000..1075d8e1 --- /dev/null +++ b/source/cprogramming/chapter6/ex_6.5.rst @@ -0,0 +1,44 @@ +=========================================================== +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:: cprogs/ex_6.5.c + :language: c + :tab-width: 4 + +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. + +:: + + key1->value1 + key2->value2 + key3->value3 + key not found + key1->value1 + key2->value2 + key not found + + + + diff --git a/source/cprogramming/chapter6/ex_6.6.rst b/source/cprogramming/chapter6/ex_6.6.rst new file mode 100644 index 00000000..57bd0970 --- /dev/null +++ b/source/cprogramming/chapter6/ex_6.6.rst @@ -0,0 +1,33 @@ +=============================== +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:: cprogs/ex_6.6.c + :language: c + :tab-width: 4 + +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. + +:: + + #define key value x + key->value + + + + 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 new file mode 100644 index 00000000..847780de --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.1_lower-upper.c @@ -0,0 +1,35 @@ +/* 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 + +/* 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) + putchar(tolower(c)); + else + 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 new file mode 100644 index 00000000..b81c952f --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.2_nongraphic.c @@ -0,0 +1,56 @@ +/** + * 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 + +#define MAXLINE 100 /* maximum number of chars in one line */ +#define OCTLEN 6 /* length of an octal value */ + +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; + + pos = 0; /* position in the line */ + + while ((c = _getchar()) != EOF) + if (iscntrl(c) || c == ' ') { + /* non-graphic or blank character */ + pos = inc(pos, OCTLEN); + printf("\\%03o", c); + /* newline character */ + if (c == '\n') + pos = 0; + putchar('\n'); + } else { + /* graphic character */ + pos = inc(pos, 1); + putchar(c); + } + return 0; +} \ 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 new file mode 100644 index 00000000..784f1f8e --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.3_minprintf.c @@ -0,0 +1,60 @@ +/* minprintf: minimalistic printf function */ +#include +#include + +void minprintf(char *fmt, ...); + +int main(void) { + char *a = "Hello,World"; + minprintf("%s", a); + int i = 10; + minprintf("%d\n", i); + int b = 011; + minprintf("b in octal: %o, and in decimal: %d\n", b, b); + int h = 10; + minprintf("h in hex: %x, and in decimal: %d\n", h, h); + return 0; +} + +void minprintf(char *fmt, ...) { + va_list ap; /* points to each unnamed arg in turn */ + char *p, *sval; + int ival; + double dval; + + va_start(ap, fmt); /* make ap point to 1st unnamed arg */ + + for (p = fmt; *p; p++) { + if (*p != '%') { + putchar(*p); + continue; + } + + 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; + } + } + 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 new file mode 100644 index 00000000..c411de31 --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.4.c @@ -0,0 +1,77 @@ +/* minscanf: minimalistic scanf function */ +#include +#include +#include + +void minscanf(char *fmt, ...); + +int main(void) { + + int i; + minscanf("%d", &i); + printf("minscanf input: %d\n", i); + + 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); + printf("minscanf input: %f\n", f); + + int o; + minscanf("%o", &o); + printf("minscanf input in octal %o, in decimal %d\n", o, o); + + int x; + minscanf("%x", &x); + printf("minscanf input in hex %x, in decimal %d\n", x, x); + return 0; +} + +void minscanf(char *fmt, ...) { + va_list ap; /* points to each unnamed arg in turn */ + char *p, *sval; + int *ival; + float *dval; + + va_start(ap, fmt); /* make ap point to 1st unnamed arg */ + + for (p = fmt; *p; p++) { + if (*p != '%') { + continue; + } + + 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; + } + } + 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 new file mode 100644 index 00000000..ddeeb038 --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.4v2.c @@ -0,0 +1,42 @@ +#include +#include +#include + +// compare two files, printing the first line where they differ +int main(int argc, char *argv[]) { + FILE *fp1, *fp2; + void filecmp(FILE *, FILE *); + char *prog = argv[0]; + if (argc == 3) { + if ((fp1 = fopen(argv[1], "r")) == NULL || + (fp2 = fopen(argv[2], "r")) == NULL) { + fprintf(stderr, "%s: can't open %s\n", prog, argv[1]); + exit(1); + } else { + filecmp(fp1, fp2); + fclose(fp1); + fclose(fp2); + } + } else { + printf("%s", "Please enter two file names"); + } + exit(0); +} + +void filecmp(FILE *f1, FILE *f2) { + size_t size = 100; + char *string; + char *string1; + + while (!feof(f1) && !feof(f2)) { + string = (char *) malloc(size); + getline(&string, &size, f1); + string1 = (char *) malloc(size); + getline(&string1, &size, f2); + if (strcmp(string, string1) != 0) { + printf("%s", string); + printf("%s", string1); + return; + } + } +} diff --git a/source/cprogramming/chapter7/cprogs/ex_7.5.c b/source/cprogramming/chapter7/cprogs/ex_7.5.c new file mode 100644 index 00000000..b676809a --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.5.c @@ -0,0 +1,132 @@ +/* + * Rewrite the postfix calculator of Chapter 4 to use scanf and/or sscanf to do + * the input and number conversion. + */ +#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 */ +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; + } + } +} + +#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) { + char c; + if (bufp > 0) { + return buf[--bufp]; + } else { + scanf("%c", &c); + return c; + } +} + +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; +} diff --git a/source/cprogramming/chapter7/cprogs/ex_7.6.c b/source/cprogramming/chapter7/cprogs/ex_7.6.c new file mode 100644 index 00000000..cc30ae1e --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.6.c @@ -0,0 +1,50 @@ +/* Write a program to compare two files, printing the first line where + * they differ. + */ + +#include + +int main(int argc, char *argv[]) { + FILE *fp1, *fp2; + void filecmp(FILE *, FILE *); + + if (argc == 1) { + /* no args; copy standard input */ + printf("Please provide two files"); + return 1; + } else + while (--argc > 0) { + if ((fp1 = fopen(argv[1], "r")) == NULL) { + printf("cat: can't open %s\n", *argv); + return 1; + } + + if ((fp2 = fopen(argv[2], "r")) == NULL) { + printf("cat: can't open %s\n", *argv); + return 1; + } + filecmp(fp1, fp2); + fclose(fp1); + fclose(fp2); + } + + return 0; +} + +void filecmp(FILE *fp1, FILE *fp2) { + int f1, f2; + while (1) { + if ((f1 = getc(fp1)) == EOF) + break; + if ((f2 = getc(fp2)) == EOF) + break; + + /* TODO: Senthil Print the full sentence */ + + if (f1 != f2) { + putchar(f1); + putchar(f2); + break; + } + } +} diff --git a/source/cprogramming/chapter7/cprogs/ex_7.7.c b/source/cprogramming/chapter7/cprogs/ex_7.7.c new file mode 100644 index 00000000..ad5e58a5 --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.7.c @@ -0,0 +1,66 @@ +/* + * 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? + */ + +#include +#include +#include +#include + +#define MAXLINE 1000 + +int mgetline(char *line, int max); + +int strindex(char *s, char *t); + +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++; + } + + return 0; +} + +/* 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/chapter7/cprogs/ex_7.8.c b/source/cprogramming/chapter7/cprogs/ex_7.8.c new file mode 100644 index 00000000..16e90427 --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.8.c @@ -0,0 +1,61 @@ +/* + * 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. + * + */ + +#include +#include +#include + +#define LINELENGTH 80 +#define LINESPERPAGE 10 + +void printpages(FILE *, FILE *); + +int main(int argc, char *argv[]) { + FILE *fp; + char *prog = argv[0]; + int linecount = 0; + + if (argc == 1) /* no args; copy standard input */ + { + fprintf(stderr, "No files given"); + printpages(stdin, stdout); + } else + while (--argc > 0) + if ((fp = fopen(*++argv, "r")) == NULL) { + fprintf(stderr, "%s: can't open %s\n", prog, *argv); + exit(1); + } else { + fprintf(stdout, "\n\n\t\t\tFile: %s\n\n", *argv); + printpages(fp, stdout); + fclose(fp); + } + + if (ferror(stdout)) { + fprintf(stderr, "%s: error writing stdout\n", prog); + exit(2); + } + exit(0); +} + +/* filecopy: copy file ifp to file ofp */ + +void printpages(FILE *ifp, FILE *ofp) { + int c; + int line = 0; + int pg = 1; + + while ((c = getc(ifp)) != EOF) { + putc(c, ofp); + if (c == '\n') { + line = line + 1; + if (line == LINESPERPAGE) { + fprintf(stdout, "\n\t\t\tPage %d End.\n\n", pg); + pg = pg + 1; + line = 0; + } + } + } +} diff --git a/source/cprogramming/chapter7/cprogs/ex_7.9.c b/source/cprogramming/chapter7/cprogs/ex_7.9.c new file mode 100644 index 00000000..acd7a805 --- /dev/null +++ b/source/cprogramming/chapter7/cprogs/ex_7.9.c @@ -0,0 +1,43 @@ +/* + * Functions like isupper can be implemented to save space or to save time. + * Explore both possibilities. + */ + +#include +#include + +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 = custom_getchar()) != 'x') { + if (c == '\n') + continue; + + if (myisupper(c) == 1) + printf("true\n"); + else + printf("false\n"); + } + return EXIT_SUCCESS; +} + +int myisupper(int c) { + if (c >= 'A' && c <= 'Z') + return 1; + else + return 0; +} diff --git a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst new file mode 100644 index 00000000..57861866 --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst @@ -0,0 +1,35 @@ +========================================================= +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:: cprogs/ex_7.1_lower-upper.c + :language: c + :tab-width: 4 + +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 + + + diff --git a/source/cprogramming/chapter7/ex_7.2_nongraphic.rst b/source/cprogramming/chapter7/ex_7.2_nongraphic.rst new file mode 100644 index 00000000..b05c5af4 --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.2_nongraphic.rst @@ -0,0 +1,30 @@ +=================================================================== +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:: cprogs/ex_7.2_nongraphic.c + :language: c + :tab-width: 4 + +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 +========= + +.. raw:: html + + diff --git a/source/cprogramming/chapter7/ex_7.3_minprintf.rst b/source/cprogramming/chapter7/ex_7.3_minprintf.rst new file mode 100644 index 00000000..7deafb80 --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.3_minprintf.rst @@ -0,0 +1,28 @@ +======================================================= +Exercise 7.3 - minprintf to handle facilities of printf +======================================================= + +Question +======== + +Revise minprintf to handle more of the other facilities of printf. + +.. literalinclude:: cprogs/ex_7.3_minprintf.c + :language: c + :tab-width: 4 + +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 + + + + diff --git a/source/cprogramming/chapter7/ex_7.4.rst b/source/cprogramming/chapter7/ex_7.4.rst new file mode 100644 index 00000000..d65cdcd7 --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.4.rst @@ -0,0 +1,56 @@ +======================================= +Exercise 7.4 - private version of scanf +======================================= + + +Question +======== + +Write a private version of scanf analogous to minprintf from the previous +section. + +.. literalinclude:: cprogs/ex_7.4.c + :language: c + :tab-width: 4 + +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 + + + + diff --git a/source/cprogramming/chapter7/ex_7.5.rst b/source/cprogramming/chapter7/ex_7.5.rst new file mode 100644 index 00000000..fc6ba70e --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.5.rst @@ -0,0 +1,40 @@ +============================================= +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:: cprogs/ex_7.5.c + :language: c + :tab-width: 4 + +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; + } + } + + + + diff --git a/source/cprogramming/chapter7/ex_7.6.rst b/source/cprogramming/chapter7/ex_7.6.rst new file mode 100644 index 00000000..20ef0199 --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.6.rst @@ -0,0 +1,29 @@ +================================ +Exercise 7.6 - Compare Two files +================================ + +Question +======== + +Write a program to compare two files, printing the first line where they differ. + +.. literalinclude:: cprogs/ex_7.6.c + :language: c + :tab-width: 4 + +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; + } + + diff --git a/source/cprogramming/chapter7/ex_7.7.rst b/source/cprogramming/chapter7/ex_7.7.rst new file mode 100644 index 00000000..1d97af41 --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.7.rst @@ -0,0 +1,24 @@ +================================================== +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:: cprogs/ex_7.7.c + :language: c + :tab-width: 4 + +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. + + + + diff --git a/source/cprogramming/chapter7/ex_7.8.rst b/source/cprogramming/chapter7/ex_7.8.rst new file mode 100644 index 00000000..d32c2722 --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.8.rst @@ -0,0 +1,71 @@ +=================================== +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:: cprogs/ex_7.8.c + :language: c + :tab-width: 4 + +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) + + + + diff --git a/source/cprogramming/chapter7/ex_7.9.rst b/source/cprogramming/chapter7/ex_7.9.rst new file mode 100644 index 00000000..6f98e1b4 --- /dev/null +++ b/source/cprogramming/chapter7/ex_7.9.rst @@ -0,0 +1,38 @@ +================================================= +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:: cprogs/ex_7.9.c + :language: c + :tab-width: 4 + + +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 + + + + 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.1_mycat.c b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c new file mode 100644 index 00000000..164b937f --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include + +#define STDIN 0 +#define STDOUT 1 +#define STDERR 2 + +/* error: print an error message and die */ +void error(char *fmt, ...) { + /* standard method to print error message with variable argument list. */ + va_list args; + va_start(args, fmt); + + fprintf((FILE *) STDERR, "error: "); + + vfprintf((FILE *) STDERR, fmt, args); + fprintf((FILE *) STDERR, "\n"); + va_end(args); + exit(1); +} + +/* filecopy: copy file ifd to ofd */ +void filecopy(int ifd, int ofd) { + int n; + char buf[BUFSIZ]; + + /* read and write using the system calls. */ + + while ((n = read(ifd, buf, BUFSIZ)) > 0) + if (write(ofd, buf, n) != n) { + error("cat: write error"); + } +} + +/* cat: concatenate files - read/write/open/close */ +int main(int argc, char *argv[]) { + int fd; + + if (argc == 1) { + /* get from stdin and write to stdout. */ + filecopy(STDIN, STDOUT); + } else + /* cat all the files one by one. */ + while (--argc > 0) + if ((fd = open(*++argv, O_RDONLY)) == -1) { + error("cat:can't open %s", *argv); + } else { + filecopy(fd, STDOUT); + 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 new file mode 100644 index 00000000..df888546 --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/ex_8.2.c @@ -0,0 +1,138 @@ +#include +#include + +#ifdef NULL +#undef NULL +#endif + +#define NULL 0 +#define EOF (-1) +#define BUFSIZE 1024 +#define OPEN_MAX 20 /* max # files open at once */ + +typedef struct _iobuf { + int cnt; /* characters left */ + char *ptr; /* next character position */ + char *base; /* location of the buffer */ + int flag; /* mode of the file access */ + int fd; /* file descriptor */ +} FILE; + +extern FILE _iob[OPEN_MAX]; + +#define stdin (&_iob[0]) +#define stdout (&_iob[1]) + +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*/ +}; + +int _fillbuf(FILE *); + +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) + +/* _fillbuf: allocate and fill input buffer */ + +int _fillbuf(FILE *fp) { + int bufsize; + + /* this is a bit operation */ + + if ((fp->flag & (_READ | _EOF | _ERR)) != _READ) + return EOF; + + /* this is a bit operation */ + + bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZE; + + if (fp->base == NULL) /* no buffer yet */ + if ((fp->base = (char *) malloc(bufsize)) == NULL) + return EOF; /* can't get buffer */ + + fp->ptr = fp->base; + fp->cnt = read(fp->fd, fp->ptr, bufsize); + + /* these are bit operations */ + + if (--fp->cnt < 0) { + if (fp->cnt == -1) + fp->flag |= _EOF; + else + fp->flag |= _ERR; + fp->cnt = 0; + return EOF; + } + + return (unsigned char) *fp->ptr++; +} + +/* _flushbuf: flush a buffer */ +/* http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_8:Exercise_3 */ + +int _flushbuf(int c, FILE *f) { + int num_written, bufsize; + unsigned char uc = c; + + if ((f->flag & (_WRITE | _EOF | _ERR)) != _WRITE) { + return EOF; + } + + if (f->base == NULL && ((f->flag & _UNBUF) == 0)) { + /* no buffer yet */ + if ((f->base = malloc(BUFSIZE)) == NULL) + /* could not allocate a buffer, so try unbuffered */ + f->flag |= _UNBUF; + else { + f->ptr = f->base; + f->cnt = BUFSIZE - 1; + } + } + + if (f->flag & _UNBUF) { + /* unbuffered write */ + f->ptr = f->base = NULL; + f->cnt = 0; + if (c == EOF) { + return EOF; + } + num_written = write(f->fd, &uc, 1); + bufsize = 1; + } else { + /* buffered write */ + /*if ( c!= EOF) { + f->ptr = uc; + } */ + bufsize = (int) (f->ptr - f->base); + num_written = write(f->fd, f->base, bufsize); + f->ptr = f->base; + f->cnt = BUFSIZE - 1; + } + + if (num_written == bufsize) + return c; + else { + f->flag |= _ERR; + return EOF; + } +} + +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}}; + +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 new file mode 100644 index 00000000..945b99c5 --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/ex_8.3.c @@ -0,0 +1,217 @@ +#include +#include +#include + +#ifdef NULL +#undef NULL +#endif + +#define NULL 0 +#define EOF (-1) +#define BUFSIZ 1024 +#define OPEN_MAX 20 /* max # files open at once */ + +typedef struct _iobuf { + int cnt; /* characters left */ + char *ptr; /* next character position */ + char *base; /* location of the buffer */ + int flag; /* mode of the file access */ + int fd; /* file descriptor */ +} FILE; + +extern FILE _iob[OPEN_MAX]; + +#define stdin (&_iob[0]) +#define stdout (&_iob[1]) + +enum _flags { + _READ = 01, /* file open for reading */ + _WRITE = 02, /* file open for writing */ + _UNBUF = 03, /* file is unbuffered */ + _EOF = 010, /* EOF has occurred on this file */ + _ERR = 020, /* error occurred on this file */ +}; + +int _fillbuf(FILE *); + +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; + + 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) { + int bufsize; + + if ((fp->flag & (_READ | _EOF | _ERR)) != _READ) + return EOF; + + bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZ; + + if (fp->base == NULL) /* no buffer yet */ + if ((fp->base = (char *) malloc(bufsize)) == NULL) + return EOF; /* can't get buffer */ + + fp->ptr = fp->base; + fp->cnt = read(fp->fd, fp->ptr, bufsize); + + if (--fp->cnt < 0) { + if (fp->cnt == -1) + fp->flag |= _EOF; + else + fp->flag |= _ERR; + fp->cnt = 0; + return EOF; + } + + return (unsigned char) *fp->ptr++; +} + +/* _flushbuf: flush a buffer */ +/* http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_8:Exercise_3 */ + +int _flushbuf(int c, FILE *f) { + int num_written, bufsize; + unsigned char uc = c; + + if ((f->flag & (_WRITE | _EOF | _ERR)) != _WRITE) { + return EOF; + } + + if (f->base == NULL && ((f->flag & _UNBUF) == 0)) { + /* no buffer yet */ + if ((f->base = malloc(BUFSIZ)) == NULL) + /* could not allocate a buffer, so try unbuffered */ + f->flag |= _UNBUF; + else { + f->ptr = f->base; + f->cnt = BUFSIZ - 1; + } + } + + if (f->flag & _UNBUF) { + /* unbuffered write */ + f->ptr = f->base = NULL; + f->cnt = 0; + if (c == EOF) { + return EOF; + } + num_written = write(f->fd, &uc, 1); + bufsize = 1; + } else { + /* buffered write */ + /* TODO: Senthil Kumaran - What should be the f-> ptr?*/ + /*if ( c!= EOF) { + f->ptr = uc; + } */ + bufsize = (int) (f->ptr - f->base); + num_written = write(f->fd, f->base, bufsize); + f->ptr = f->base; + f->cnt = BUFSIZ - 1; + } + + if (num_written == bufsize) + return c; + else { + f->flag |= _ERR; + return EOF; + } +} + +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}}; + +/* fflush */ +int fflush(FILE *f) { + int retval; + int i; + FILE *fp; + + retval = 0; + + if (f == NULL) { + /* flush all the output streams */ + + for (fp = _iob; fp < _iob + OPEN_MAX; fp++) + if ((fp->flag & _WRITE) == 0 && fflush(fp) == -1) + retval = -1; + } else { + if ((f->flag & _WRITE) == 0) + return -1; + _flushbuf(EOF, f); + if (f->flag & _ERR) + retval = -1; + } + return retval; +} + +/* fclose */ + +int fclose(FILE *f) { + int fd; + + if (f == NULL) + return -1; + + fd = f->fd; + fflush(f); + f->cnt = 0; + f->ptr = NULL; + if (f->base != NULL) + free(f->base); + f->base = NULL; + f->flag = 0; + f->fd = -1; + return close(fd); +} + +int main(int argc, char *argv[]) { + int c; + while ((c = getchar()) != 'x') { + putchar(c); + } +} diff --git a/source/cprogramming/chapter8/cprogs/ex_8.4.c b/source/cprogramming/chapter8/cprogs/ex_8.4.c new file mode 100644 index 00000000..b99f651e --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/ex_8.4.c @@ -0,0 +1,269 @@ +#include +#include +// The functions available from stdio.h are implemented here. +//#include +#include +#include +#include + +#ifdef NULL +#undef NULL +#endif + +#define NULL 0 +#define EOF (-1) +#define BUFSIZ 1024 +#define OPEN_MAX 20 /* max # files open at once */ + +typedef struct _iobuf { + int cnt; /* characters left */ + char *ptr; /* next character position */ + char *base; /* location of the buffer */ + int flag; /* mode of the file access */ + int fd; /* file descriptor */ +} FILE; + +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 */ + _WRITE = 02, /* file open for writing */ + _UNBUF = 03, /* file is unbuffered */ + _EOF = 010, /* EOF has occurred on this file */ + _ERR = 020, /* error occurred on this file */ +}; + +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) + +#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; + + 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) { + int bufsize; + + if ((fp->flag & (_READ | _EOF | _ERR)) != _READ) + return EOF; + + bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZ; + + if (fp->base == NULL) /* no buffer yet */ + if ((fp->base = (char *)malloc(bufsize)) == NULL) + return EOF; /* can't get buffer */ + + fp->ptr = fp->base; + fp->cnt = read(fp->fd, fp->ptr, bufsize); + + if (--fp->cnt < 0) { + if (fp->cnt == -1) + fp->flag |= _EOF; + else + fp->flag |= _ERR; + fp->cnt = 0; + return EOF; + } + + return (unsigned char)*fp->ptr++; +} + +/* _flushbuf: flush a buffer */ +/* http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_8:Exercise_3 */ + +int _flushbuf(int c, FILE *f) { + int num_written, bufsize; + unsigned char uc = c; + + if ((f->flag & (_WRITE | _EOF | _ERR)) != _WRITE) { + return EOF; + } + + if (f->base == NULL && ((f->flag & _UNBUF) == 0)) { + /* no buffer yet */ + if ((f->base = malloc(BUFSIZ)) == NULL) + /* could not allocate a buffer, so try unbuffered */ + f->flag |= _UNBUF; + else { + f->ptr = f->base; + f->cnt = BUFSIZ - 1; + } + } + + if (f->flag & _UNBUF) { + /* unbuffered write */ + f->ptr = f->base = NULL; + f->cnt = 0; + if (c == EOF) { + return EOF; + } + num_written = write(f->fd, &uc, 1); + bufsize = 1; + } else { + /* buffered write */ + /* TODO: Senthil Kumaran - What should be the f-> ptr?*/ + /*if ( c!= EOF) { + f->ptr = uc; + } */ + bufsize = (int)(f->ptr - f->base); + num_written = write(f->fd, f->base, bufsize); + f->ptr = f->base; + f->cnt = BUFSIZ - 1; + } + + if (num_written == bufsize) + return c; + else { + f->flag |= _ERR; + return EOF; + } +} + +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}}; + +/* fflush */ +int fflush(FILE *f) { + int retval; + int i; + FILE *fp; + + retval = 0; + + if (f == NULL) { + /* flush all the output streams */ + + for (fp = _iob; fp < _iob + OPEN_MAX; fp++) + if ((fp->flag & _WRITE) == 0 && fflush(fp) == -1) + retval = -1; + } else { + if ((f->flag & _WRITE) == 0) + return -1; + _flushbuf(EOF, f); + if (f->flag & _ERR) + retval = -1; + } + return retval; +} + +/* fclose */ + +int fclose(FILE *f) { + int fd; + + if (f == NULL) + return -1; + + fd = f->fd; + fflush(f); + f->cnt = 0; + f->ptr = NULL; + if (f->base != NULL) + free(f->base); + f->base = NULL; + f->flag = 0; + f->fd = -1; + return close(fd); +} + +/* fseek */ +/* http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_8:Exercise_4 */ +#define SEEK_SET 0 +#define SEEK_CUR 1 +#define SEEK_END 2 + +int fseek(FILE *f, long offset, int whence) { + int result; + + if ((f->flag & _UNBUF) == 0 && f->base != NULL) { + /* deal with buffering */ + if (f->flag & _WRITE) { + if (fflush(f)) + return EOF; + } else if (f->flag & _READ) { + /* Reading so thrash buffer, do some housekeeping first + */ + if (whence == SEEK_CUR) { + /* fix offset so that it's from the last + * character the user read (not the last character that was + * actually read) + */ + if (offset >= 0 && offset <= f->cnt) { + /* easy shortcut */ + f->cnt -= offset; + f->ptr += offset; + f->flag &= ~_EOF; /* If successful, clear EOF */ + return 0; + } else { + offset -= f->cnt; + } + } + f->cnt = 0; + f->ptr = f->base; + } + } + + result = (lseek(f->fd, offset, whence) < 0); + + if (result == 0) + f->flag &= ~_EOF; /* If successful, clear EOF */ + return result; +} + +int main(int argc, char *argv[]) { + int c; + while ((c = getchar()) != 'x') { + putchar(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 new file mode 100644 index 00000000..8ed7cdc8 --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/ex_8.6_calloc.c @@ -0,0 +1,43 @@ +/* The standard library function calloc(n,size) returns a pointer to n objects +/* if size size, with the storage intialized to zero. Write calloc,by callinng +/* malloc or modifying it */ + +/* calloc: allocate n objects of size size */ + +#include +#include + +void *mycalloc(unsigned, unsigned); + +void *mycalloc(unsigned n, unsigned size) { + unsigned i, nb; + char *p, *q; + + nb = n * size; + + if ((p = q = malloc(nb)) != NULL) + for (i = 0; i < nb; i++) + *p++ = 0; + return q; +} + +int main(int argc, char *argv[]) { + int *p = NULL; + int i = 0; + + p = mycalloc(100, sizeof *p); + if (NULL == p) { + printf("mycalloc returned NULL"); + + } else { + for (i = 0; i <= 100; i++) { + printf("%08X", p[i]); + if (i % 8 == 7) { + printf("\n"); + } + } + printf("\n"); + free(p); + } + return 0; +} diff --git a/source/cprogramming/chapter8/cprogs/ex_8.7_malloc.c b/source/cprogramming/chapter8/cprogs/ex_8.7_malloc.c new file mode 100644 index 00000000..fe0fd30f --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/ex_8.7_malloc.c @@ -0,0 +1,125 @@ +/* malloc accepts a size request without checking its plausiblity; free believes + that the block it is asked to free contain a valid size field. Improve these + rountines so they take more pains with error checking */ + +#include +#include + +#define MAXBYTES (unsigned)10240 +#define NALLOC 1024 + +typedef long Align; + +union header { + struct { + union header *ptr; /* next block if on free list */ + unsigned size; /* size of this block */ + } s; +}; + +typedef union header Header; + +static unsigned maxalloc; /* max number of units allocated */ +static Header base; /* empty list to get started */ +static Header *freep = NULL; /*start of free list */ + +/* morecore: ask system for more memory */ + +static Header *morecore(unsigned nu) { + char *cp, *sbrk(int); + Header *up; + + if (nu < NALLOC) + nu = NALLOC; + + cp = sbrk(nu * sizeof(Header)); + if (cp == (char *) -1) /* no space at all */ + return NULL; + + up = (Header *) cp; + up->s.size = nu; + free((void *) (up + 1)); + return freep; +} + +/* malloc: general purpose storage allocator */ + +void *mymalloc(unsigned nbytes) { + Header *p, *prevp; + Header *morecore(unsigned); + unsigned nunits; + + if (nbytes > MAXBYTES) { + fprintf(stderr, "alloc: can't allocate more than %u bytes\n", MAXBYTES); + return NULL; + } + nunits = (nbytes + sizeof(Header) - 1) / sizeof(Header) + 1; + + if ((prevp = freep) == NULL) { + base.s.ptr = freep = prevp = &base; + base.s.size = 0; + } + for (p = prevp->s.ptr;; prevp = p, p = p->s.ptr) { + if (p->s.size >= nunits) { + if (p->s.size == nunits) + prevp->s.ptr = p->s.ptr; + else { + p->s.size -= nunits; + p += p->s.size; + p->s.size = nunits; + } + freep = prevp; + return (void *) (p + 1); + } + + if (p == freep) /* wrapped around free list */ + if ((p = morecore(nunits)) == NULL) + return NULL; + } +} + +/* free: put a block ap in free list */ + +void free(void *ap) { + Header *bp, *p; + + 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 */ + + if (bp + bp->s.size == p->s.ptr) { /* join to upper nbr */ + bp->s.size += p->s.ptr->s.size; + bp->s.ptr = p->s.ptr->s.ptr; + } else + bp->s.ptr = p->s.ptr; + + if (p + p->s.size == bp) { /* join to lower nbr */ + p->s.size += bp->s.size; + p->s.ptr = bp->s.ptr; + } else + p->s.ptr = bp; + + freep = p; +} + +int main(int argc, char *argv[]) { + int *p = NULL; + int i = 0; + + p = mymalloc(1000); + if (NULL == p) { + printf("mymalloc returned NULL"); + + } else { + for (i = 0; i <= 100; i++) { + printf("%08X", p[i]); + if (i % 8 == 7) { + printf("\n"); + } + } + printf("\n"); + free(p); + } + return 0; +} diff --git a/source/cprogramming/chapter8/cprogs/ex_8.8_bfree.c b/source/cprogramming/chapter8/cprogs/ex_8.8_bfree.c new file mode 100644 index 00000000..39170924 --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/ex_8.8_bfree.c @@ -0,0 +1,191 @@ +/* bfree(): Exercise from K&R 8-8. + * + * Adds an arbitrary block into the free list maintained by malloc() + * and free() as written by K&R in chapter 8. + * + * Massages the block to a format acceptable to the free() list,with the + * remaining bits (bytes) managed by Waiting To Be free()ed (wtbfree()) + * + * wtbfree() can be an empty function with the effect of simply + * discarding the chopped off bits. Only intended to be as portable as + * free() itself, or maybe less so due to the use of the ALIGN macro. + **/ + +#include +#include + +#define MAXBYTES (unsigned)1024 + +typedef long Align; + +union header { + struct { + union header *ptr; /* next block if on the free list */ + unsigned size; /* size of this block */ + } s; + Align x; +}; + +typedef union header Header; + +static Header base; /* empty list to get started */ +static Header *freep = NULL; /*start of free list */ + +#define ALIGN(p) \ + (sizeof(Align) - ((unsigned)(p) % sizeof(Align))) % sizeof(Align) + +void wtbfree(void *, unsigned); +void bfree(void *, unsigned); + +void bfree(void *p, unsigned n) { + unsigned align, s, r; + + if (n < sizeof(Header)) { /* can't free less than this */ + wtbfree(p, n); + return; + } + + align = ALIGN(p); + if (align) { /* adjust alignment */ + wtbfree(p, align); /* put at the beginning in the wtbfree list */ + p = (char *)p + align; + n -= align; + } + s = n / sizeof(Header); + r = n % sizeof(Header); + + /* put at the trailing end of the wtbfree list */ + if (r) { + wtbfree((char *)p + n + r, r); + } + /* if there is something left to be free */ + if (s) { + + if (freep == NULL) { /* Setup a free list if it is empty */ + base.s.ptr = freep = &base; + base.s.size = 0; + } + + ((Header *)p)->s.size = s; + free((Header *)p + 1); + } +} + +struct wtbheader { + struct wtbheader *next; + void *p; + unsigned n; +}; + +void try_to_free(struct wtbheader *p) { + char *tp; + unsigned align; + unsigned n; + + tp = p->p; + align = ALIGN(p->p); + + if ((align < p->n) && ((p->n - align) % sizeof(Header) == 0)) { + tp += align; + n = p->n - align; + p->n = align; + + ((Header *)tp)->s.size = n / sizeof(Header); + free((Header *)tp + 1); + } +} + +static struct wtbheader *headptr; + +void wtbfree(void *p, unsigned n) { + struct wtbheader *hp, *prevp; + + if (headptr == NULL) { /* first use */ + if (!(headptr = + malloc(sizeof *headptr))) /*can't save fragment, dump it */ + return; + headptr->p = p; + headptr->n = n; + headptr->next = NULL; + } else if (p < headptr->p) { /* Special case: less than head */ + if ((char *)p + n == headptr->p) { /* merge */ + headptr->p = p; + headptr->n = n; + try_to_free(headptr); + + if (!headptr->n) { /* delete empty node */ + void *tp = headptr; + headptr = headptr->next; + free(tp); + } + } else { + struct wtbheader *tp; + if (!(tp = malloc(sizeof *tp))) /* can't save fragment, dump it */ + return; + tp->p = p; + tp->n = n; + tp->next = headptr; + headptr = tp; + } + + } else { + for (prevp = hp = headptr; hp->next && p > hp->next->p; + prevp = hp, hp = hp->next) { + ; /* just advance */ + } + + if ((char *)hp->p + hp->n == p) { /* merge to current */ + hp->n += n; + try_to_free(hp); + + if (!hp->n) { + if (hp == headptr) + headptr = NULL; + prevp->next = hp->next; + free(hp); + } + + } else if (hp->next && + (char *)p + n == hp->next->p) { /* merge to next */ + hp->next->p = p; + hp->next->n += n; + try_to_free(hp->next); + + if (!hp->next->n) { /* delete empty node */ + void *tp = hp->next; + hp->next = hp->next->next; + free(tp); + } + } else { /* insert */ + struct wtbheader *tp; + if (!(tp = malloc(sizeof *tp))) /* can't save fragment, dump */ + return; + tp->p = p; + tp->n = n; + + tp->next = hp->next; + hp->next = tp; + } + } +} + +int main(int argc, char *argv[]) { + int *p = NULL; + int i = 0; + + p = malloc(100 * sizeof *p); + if (NULL == p) { + printf("malloc returned NULL"); + + } else { + for (i = 0; i <= 100; i++) { + printf("%08X", p[i]); + if (i % 8 == 7) { + printf("\n"); + } + } + printf("\n"); + bfree(p, 1 * sizeof *p); + } + return 0; +} diff --git a/source/cprogramming/chapter8/cprogs/sec_8.2_getchar.c b/source/cprogramming/chapter8/cprogs/sec_8.2_getchar.c new file mode 100644 index 00000000..5f615cc2 --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/sec_8.2_getchar.c @@ -0,0 +1,47 @@ +/* Example of an unbuffered and buffered getchar */ + +#include +#include +#include + +#define BUFSIZ 1024 + +/* unbuffered getchar implementation using read */ + +int ugetchar(void); + +/* buffered getchar implementation using read */ +int bgetchar(void); + +int main() { + char c; + while ((c = ugetchar()) != 'x') { + putchar(c); + } + + while ((c = bgetchar()) != 'x') { + putchar(c); + } + + return 0; +} + +int ugetchar(void) { + char c; + + return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF; +} + +int bgetchar(void) { + static char buf[BUFSIZ]; + static char *bufp = buf; + static int n = 0; + + if (n == 0) /* buffer is empty */ + { + n = read(0, buf, sizeof buf); + bufp = buf; + } + + 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 new file mode 100644 index 00000000..49618bcf --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c @@ -0,0 +1,49 @@ +#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 */ + +#define BUFSIZ 1024 + +void merror(char *, ...); + +int main(int argc, char *argv[]) { + int f1, f2, n; + char buf[BUFSIZ]; + + if (argc != 3) + merror("Usage: prog: from to"); + + if ((f1 = open(argv[1], O_RDONLY, 0)) == -1) + merror("prog: can't open %s", argv[1]); + if ((f2 = creat(argv[2], PERMS)) == -1) + merror("prog: can't create %s, mode %03o", argv[2], PERMS); + + while ((n = read(f1, buf, BUFSIZ)) > 0) + if (write(f2, buf, n) != n) + merror("prog: write error on file %s", argv[2]); + + return 0; +} + +/** +fmt is the format string parameter +... (ellipsis) indicates variable number of arguments can follow + +*/ +void merror(char *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); // Print formatted output using args list + fprintf(stderr, "\n"); + va_end(args); // cleans up variable arguments. + exit(1); +} diff --git a/source/cprogramming/chapter8/cprogs/sec_8_2_read_write.c b/source/cprogramming/chapter8/cprogs/sec_8_2_read_write.c new file mode 100644 index 00000000..35b5a2a9 --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/sec_8_2_read_write.c @@ -0,0 +1,16 @@ +/*copy input to output */ + +#include +#include + +#define BUFSIZ 1024 + +int main() /* copy input to output */ +{ + char buf[BUFSIZ]; + int n; + + while ((n = read(0, buf, BUFSIZ)) > 0) + write(1, buf, n); + return 0; +} diff --git a/source/cprogramming/chapter8/ex_8.1_mycat.rst b/source/cprogramming/chapter8/ex_8.1_mycat.rst new file mode 100644 index 00000000..a4eac327 --- /dev/null +++ b/source/cprogramming/chapter8/ex_8.1_mycat.rst @@ -0,0 +1,22 @@ +============================================================ +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:: cprogs/ex_8.1_mycat.c + :language: c + + +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 new file mode 100644 index 00000000..a6ce6a34 --- /dev/null +++ b/source/cprogramming/chapter8/ex_8.2.rst @@ -0,0 +1,21 @@ +===================================================== +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. + +.. 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 new file mode 100644 index 00000000..4454a521 --- /dev/null +++ b/source/cprogramming/chapter8/ex_8.3.rst @@ -0,0 +1,20 @@ +=========================================== +Exercise 8.3 - _flushbuf, fflush and fclose +=========================================== + +Question +======== + +Design and write _flushbuf, fflush, and fclose. + +**inprogress** + +.. literalinclude:: cprogs/ex_8.3.c + :language: c + +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 new file mode 100644 index 00000000..e8174471 --- /dev/null +++ b/source/cprogramming/chapter8/ex_8.4.rst @@ -0,0 +1,31 @@ +============================== +Exercise 8.4 - implement fseek +============================== + +Question +======== + +The standard library function: + + ``int fseek(FILE *fp, long offset, int origin)`` + +**inprogress** + + +.. literalinclude:: cprogs/ex_8.4.c + :language: c + :tab-width: 4 + +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 new file mode 100644 index 00000000..b316f08e --- /dev/null +++ b/source/cprogramming/chapter8/ex_8.5_fsize.rst @@ -0,0 +1,35 @@ +========================== +Exercise 8.5 - inode entry +========================== + +Question +======== + +Modify the fsize program to print the other information contained in the inode +entry. + + +.. literalinclude:: cprogs/ex_8.5_fsize.c + :language: c + :tab-width: 4 + +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 new file mode 100644 index 00000000..03598c58 --- /dev/null +++ b/source/cprogramming/chapter8/ex_8.6_calloc.rst @@ -0,0 +1,23 @@ +============================================== +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:: cprogs/ex_8.6_calloc.c + :language: c + :tab-width: 4 + +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 new file mode 100644 index 00000000..26622729 --- /dev/null +++ b/source/cprogramming/chapter8/ex_8.7_malloc.rst @@ -0,0 +1,26 @@ +======================================= +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:: 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 new file mode 100644 index 00000000..3613c191 --- /dev/null +++ b/source/cprogramming/chapter8/ex_8.8_bfree.rst @@ -0,0 +1,23 @@ +========================================= +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:: 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 new file mode 100644 index 00000000..95417c1f --- /dev/null +++ b/source/cprogramming/chapter8/sec_8.2_getchar.rst @@ -0,0 +1,46 @@ +============================================= +Section 8.2 - Buffered and Unbuffered getchar +============================================= + +Question +======== + +Demonstrate buffered and unbuffered getchar using the system read function. + + +.. literalinclude:: cprogs/sec_8.2_getchar.c + :language: c + + +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[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 +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 + diff --git a/source/cprogramming/chapter8/sec_8.2_read_write.rst b/source/cprogramming/chapter8/sec_8.2_read_write.rst new file mode 100644 index 00000000..343429cd --- /dev/null +++ b/source/cprogramming/chapter8/sec_8.2_read_write.rst @@ -0,0 +1,40 @@ +============================ +Section 8.2 - Read and Write +============================ + +Question +======== + +Copy input to output by using read and write system calls. + + +.. literalinclude:: cprogs/sec_8_2_read_write.c + :language: c + :tab-width: 4 + +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 new file mode 100644 index 00000000..bf6a0d22 --- /dev/null +++ b/source/cprogramming/chapter8/sec_8.3_open_creat.rst @@ -0,0 +1,24 @@ +================================= +Section 8.3 open and create calls +================================= + +Question +======== + +Demonstrate the ``cp`` like program which copies the contents of one file to another. + + +.. literalinclude:: cprogs/sec_8.3_open_creat.c + :language: c + + +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 b9912dc4..00000000 --- a/source/cprogramming/index.rst +++ /dev/null @@ -1,232 +0,0 @@ -====================== -C Programming Language -====================== - -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 - -Interesting Uncategorized Programs -================================== - -.. toctree:: - :maxdepth: 1 - - dcl - getline_woandr - mined1 - mygetchar - numlinesort - pgechov1 - pgechov2 - pgechov3 - prepro1 - prepro2 - printd - quicksort - rot13 - shellsort - sizeof_various - sort - sortv2 - squeezesc - unescape - val_limits - wumpus - makedir - long_extnal - likegrep - likefind - leap - glat17 - getpass1 - fsize - fork1 - eratosthenes - endian - day_datev3 - counts - atoiv2 - anylonglinelen - alloc_afree - Fibonacci - binsearch - bitcount - getbits 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/mined1.rst b/source/cprogramming/mined1.rst deleted file mode 100644 index bbe88663..00000000 --- a/source/cprogramming/mined1.rst +++ /dev/null @@ -1,16 +0,0 @@ -====== -mined1 -====== - -*mined1.c* - -.. literalinclude:: ../../languages/cprogs/mined1.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`mined1.c` - * :c-better-explain:`mined1.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_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 9444aa97..00000000 --- a/source/cprogramming/sec_8.3_open_creat.rst +++ /dev/null @@ -1,34 +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 - - -:use-local-compiler:`gcc` - -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 68259f03..a5ee9335 100644 --- a/source/index.rst +++ b/source/index.rst @@ -1,59 +1,28 @@ -Learn, Understand and Solve Problems -==================================== +Learn To Solve It +================= -This website contains example of snippets and explainations. The idea is to -learn, understand and solve problems. These small pieces are often the building -blocks of larger solutions. +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. -The problems are taken from well known sources, exercises in books. The -copyright of those problems belongs to author of the books. - -The solutions are either written by me, contributors or copied from other -places. If they are copied, I attribute with reference. If it is missing, I -apologize, and I will correct it. The explaination are written by me and other -contributors. - -Improvements to website can be submitted via `Github`_ pull requests. +I recommend https://exercism.org as the platform to learn Programming and +practice with a dedicated community. **Reference Books** * C Programming Language by Kernighan and Ritchie. -* Python Cookbook by Alex Martelli, Anna Martelli Ravenscroft, and David Ascher. -* Java Precisely by Peter Sestoft. - -.. _Learn To Solve It: http://www.learntosolveit.com -.. _ideone: http://www.ideone.com -.. _Github: https://github.com/uthcode/learntosolveit - - -C Programming Language -====================== - -.. toctree:: - :maxdepth: 3 - - cprogramming/index - -Python Programming Language -=========================== - -.. toctree:: - :maxdepth: 3 - - python/index - -Ruby Programming Language -========================= - -.. toctree:: - :maxdepth: 3 - - ruby/index -Java Programming Language -========================= +C Programming +============= .. toctree:: :maxdepth: 3 - java/index + ./cprogramming/chapter1/index.rst + ./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/java/AbstractClass.rst b/source/java/AbstractClass.rst deleted file mode 100644 index 67351d15..00000000 --- a/source/java/AbstractClass.rst +++ /dev/null @@ -1,32 +0,0 @@ -============== -Abstract Class -============== - -Question -======== - -Show an example of using AbstractClass in Java. - -Solution -======== - -.. literalinclude:: ../../languages/java/AbstractClass.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/AbstractClass.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :java-suggest-improve:`AbstractClass.java` - * :java-better-explain:`AbstractClass.rst` - diff --git a/source/java/AlignNumbers.rst b/source/java/AlignNumbers.rst deleted file mode 100644 index 6de61521..00000000 --- a/source/java/AlignNumbers.rst +++ /dev/null @@ -1,31 +0,0 @@ -============================================ -Aligning Numbers in Columns using out.format -============================================ - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/AlignNumbers.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/AlignNumbers.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Alignnumbers.java` - * :java-better-explain:`Alignnumbers.rst` - diff --git a/source/java/AligningStrings.rst b/source/java/AligningStrings.rst deleted file mode 100644 index e3cc17a1..00000000 --- a/source/java/AligningStrings.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Aligning Strings -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/AligningStrings.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/AligningStrings.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`AligningStrings.java` - * :java-better-explain:`AligningStrings.rst` - diff --git a/source/java/AllPathsTryCatchFinally.rst b/source/java/AllPathsTryCatchFinally.rst deleted file mode 100644 index 8934a325..00000000 --- a/source/java/AllPathsTryCatchFinally.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========================== -All Paths Try Catch Finally -=========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/AllPathsTryCatchFinally.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/AllPathsTryCatchFinally.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`AllPathsTryCatchFinally.java` - * :java-better-explain:`AllPathsTryCatchFinally.rst` - diff --git a/source/java/AnimatedCanvas.rst b/source/java/AnimatedCanvas.rst deleted file mode 100644 index 4ac47234..00000000 --- a/source/java/AnimatedCanvas.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Animated Canvas -=============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/AnimatedCanvas.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/AnimatedCanvas.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`AnimatedCanvas.java` - * :java-better-explain:`AnimatedCanvas.rst` - diff --git a/source/java/ArithmeticOperators.rst b/source/java/ArithmeticOperators.rst deleted file mode 100644 index a66702f0..00000000 --- a/source/java/ArithmeticOperators.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Arithmetic Operators -==================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ArithmeticOperators.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ArithmeticOperators.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ArithmeticOperators.java` - * :java-better-explain:`ArithmeticOperators.rst` - diff --git a/source/java/ArrayAssignmentTypeCheck.rst b/source/java/ArrayAssignmentTypeCheck.rst deleted file mode 100644 index 329a3709..00000000 --- a/source/java/ArrayAssignmentTypeCheck.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========================== -Array Assignment Type Check -=========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ArrayAssignmentTypeCheck.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ArrayAssignmentTypeCheck.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ArrayAssignmentTypeCheck.java` - * :java-better-explain:`ArrayAssignmentTypeCheck.rst` - diff --git a/source/java/AssignmentNoCopyObjects.rst b/source/java/AssignmentNoCopyObjects.rst deleted file mode 100644 index c8eabff4..00000000 --- a/source/java/AssignmentNoCopyObjects.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Assignment No Copy Objects -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/AssignmentNoCopyObjects.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/AssignmentNoCopyObjects.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`AssignmentNoCopyObjects.java` - * :java-better-explain:`AssignmentNoCopyObjects.rst` - diff --git a/source/java/AutoBoxingUnboxing.rst b/source/java/AutoBoxingUnboxing.rst deleted file mode 100644 index ba14eeb7..00000000 --- a/source/java/AutoBoxingUnboxing.rst +++ /dev/null @@ -1,34 +0,0 @@ -================================ -Example 3 - Auto Boxing Unboxing -================================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/AutoBoxingUnboxing.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/AutoBoxingUnboxing.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`AutoBoxingUnboxing.java` - * :java-better-explain:`AutoBoxingUnboxing.rst` - diff --git a/source/java/BinaryOutput.rst b/source/java/BinaryOutput.rst deleted file mode 100644 index 4c798b82..00000000 --- a/source/java/BinaryOutput.rst +++ /dev/null @@ -1,34 +0,0 @@ -============= -Binary Output -============= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/BinaryOutput.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/BinaryOutput.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`BinaryOutput.java` - * :java-better-explain:`BinaryOutput.rst` - diff --git a/source/java/BinarySearchSortedArray.rst b/source/java/BinarySearchSortedArray.rst deleted file mode 100644 index 231562c3..00000000 --- a/source/java/BinarySearchSortedArray.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Binary Search Sorted Array -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/BinarySearchSortedArray.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/BinarySearchSortedArray.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`BinarySearchSortedArray.java` - * :java-better-explain:`BinarySearchSortedArray.rst` - diff --git a/source/java/BitwiseOperators.rst b/source/java/BitwiseOperators.rst deleted file mode 100644 index 49e9de33..00000000 --- a/source/java/BitwiseOperators.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Bitwise Operators -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/BitwiseOperators.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/BitwiseOperators.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`BitwiseOperators.java` - * :java-better-explain:`BitwiseOperators.rst` - diff --git a/source/java/BlockStatements.rst b/source/java/BlockStatements.rst deleted file mode 100644 index 8aff22b5..00000000 --- a/source/java/BlockStatements.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Block Statements -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/BlockStatements.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/BlockStatements.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`BlockStatements.java` - * :java-better-explain:`BlockStatements.rst` - diff --git a/source/java/BuildingConcordance.rst b/source/java/BuildingConcordance.rst deleted file mode 100644 index 3e6ea2a3..00000000 --- a/source/java/BuildingConcordance.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Building Concordance -==================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/BuildingConcordance.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/BuildingConcordance.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`BuildingConcordance.java` - * :java-better-explain:`BuildingConcordance.rst` - diff --git a/source/java/CallingNonOverloaded.rst b/source/java/CallingNonOverloaded.rst deleted file mode 100644 index 53b09405..00000000 --- a/source/java/CallingNonOverloaded.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Calling Non Overloaded -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/CallingNonOverloaded.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/CallingNonOverloaded.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`CallingNonOverloaded.java` - * :java-better-explain:`CallingNonOverloaded.rst` - diff --git a/source/java/CallingOverloaded.rst b/source/java/CallingOverloaded.rst deleted file mode 100644 index a7ffb562..00000000 --- a/source/java/CallingOverloaded.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Calling Overloaded -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/CallingOverloaded.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/CallingOverloaded.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`CallingOverloaded.java` - * :java-better-explain:`CallingOverloaded.rst` - diff --git a/source/java/CallingOverriddenConstructor.rst b/source/java/CallingOverriddenConstructor.rst deleted file mode 100644 index 7c96e710..00000000 --- a/source/java/CallingOverriddenConstructor.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================== -Calling Overridden Constructor -============================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/CallingOverriddenConstructor.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/CallingOverriddenConstructor.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`CallingOverriddenConstructor.java` - * :java-better-explain:`CallingOverriddenConstructor.rst` - diff --git a/source/java/CallingOverriden.rst b/source/java/CallingOverriden.rst deleted file mode 100644 index 91c7a5d2..00000000 --- a/source/java/CallingOverriden.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Calling Overriden -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/CallingOverriden.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/CallingOverriden.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`CallingOverriden.java` - * :java-better-explain:`CallingOverriden.rst` - diff --git a/source/java/ClassesInterfaces.rst b/source/java/ClassesInterfaces.rst deleted file mode 100644 index 746cf3c6..00000000 --- a/source/java/ClassesInterfaces.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Classes Interfaces -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ClassesInterfaces.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ClassesInterfaces.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ClassesInterfaces.java` - * :java-better-explain:`ClassesInterfaces.rst` - diff --git a/source/java/Comments.rst b/source/java/Comments.rst deleted file mode 100644 index 991e3fd7..00000000 --- a/source/java/Comments.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Example 1 - Comments -==================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Comments.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Comments.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Comments.java` - * :java-better-explain:`Comments.rst` - diff --git a/source/java/CompleteInputOutput.rst b/source/java/CompleteInputOutput.rst deleted file mode 100644 index 8c7bade5..00000000 --- a/source/java/CompleteInputOutput.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Complete Input Output -===================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/CompleteInputOutput.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/CompleteInputOutput.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`CompleteInputOutput.java` - * :java-better-explain:`CompleteInputOutput.rst` - diff --git a/source/java/CompoundAssignment.rst b/source/java/CompoundAssignment.rst deleted file mode 100644 index 4d39fc9d..00000000 --- a/source/java/CompoundAssignment.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Compound Assignment -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/CompoundAssignment.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/CompoundAssignment.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`CompoundAssignment.java` - * :java-better-explain:`CompoundAssignment.rst` - diff --git a/source/java/ConcatCliArgs.rst b/source/java/ConcatCliArgs.rst deleted file mode 100644 index d3afcacc..00000000 --- a/source/java/ConcatCliArgs.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Concat CliArgs -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ConcatCliArgs.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ConcatCliArgs.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ConcatCliArgs.java` - * :java-better-explain:`ConcatCliArgs.rst` - diff --git a/source/java/Concatenate.rst b/source/java/Concatenate.rst deleted file mode 100644 index a47ac9b9..00000000 --- a/source/java/Concatenate.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Example 9 - Concatenate -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Concatenate.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Concatenate.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Concatenate.java` - * :java-better-explain:`Concatenate.rst` - diff --git a/source/java/ConcordanceUsingIterables.rst b/source/java/ConcordanceUsingIterables.rst deleted file mode 100644 index e962b61c..00000000 --- a/source/java/ConcordanceUsingIterables.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========================== -Concordance Using Iterables -=========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ConcordanceUsingIterables.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ConcordanceUsingIterables.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ConcordanceUsingIterables.java` - * :java-better-explain:`ConcordanceUsingIterables.rst` - diff --git a/source/java/ConcreteCollection.rst b/source/java/ConcreteCollection.rst deleted file mode 100644 index 75ea1c1f..00000000 --- a/source/java/ConcreteCollection.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Concrete Collection -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ConcreteCollection.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ConcreteCollection.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ConcreteCollection.java` - * :java-better-explain:`ConcreteCollection.rst` - diff --git a/source/java/ConditionalExpression.rst b/source/java/ConditionalExpression.rst deleted file mode 100644 index cfb4bbb7..00000000 --- a/source/java/ConditionalExpression.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Conditional Expression -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ConditionalExpression.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ConditionalExpression.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ConditionalExpression.java` - * :java-better-explain:`ConditionalExpression.rst` - diff --git a/source/java/ConstraintsType.rst b/source/java/ConstraintsType.rst deleted file mode 100644 index ec944e7f..00000000 --- a/source/java/ConstraintsType.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Constraints Type -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ConstraintsType.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ConstraintsType.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ConstraintsType.java` - * :java-better-explain:`ConstraintsType.rst` - diff --git a/source/java/ConstructorOverloading.rst b/source/java/ConstructorOverloading.rst deleted file mode 100644 index d8e82b35..00000000 --- a/source/java/ConstructorOverloading.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Constructor Overloading -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ConstructorOverloading.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ConstructorOverloading.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ConstructorOverloading.java` - * :java-better-explain:`ConstructorOverloading.rst` - diff --git a/source/java/ConversionPrimitive.rst b/source/java/ConversionPrimitive.rst deleted file mode 100644 index 053a250d..00000000 --- a/source/java/ConversionPrimitive.rst +++ /dev/null @@ -1,34 +0,0 @@ -================================ -Example 4 - Conversion Primitive -================================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ConversionPrimitive.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ConversionPrimitive.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ConversionPrimitive.java` - * :java-better-explain:`ConversionPrimitive.rst` - diff --git a/source/java/CountEs.rst b/source/java/CountEs.rst deleted file mode 100644 index a61ebdf6..00000000 --- a/source/java/CountEs.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================================== -Example 10 - Count the Number of Es -=================================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/CountEs.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/CountEs.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`CountEs.java` - * :java-better-explain:`CountEs.rst` - diff --git a/source/java/DeclaringCheckedException.rst b/source/java/DeclaringCheckedException.rst deleted file mode 100644 index 594094bc..00000000 --- a/source/java/DeclaringCheckedException.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========================== -Declaring Checked Exception -=========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/DeclaringCheckedException.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/DeclaringCheckedException.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`DeclaringCheckedException.java` - * :java-better-explain:`DeclaringCheckedException.rst` - diff --git a/source/java/Describe.rst b/source/java/Describe.rst deleted file mode 100644 index 8d0e7561..00000000 --- a/source/java/Describe.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Describe -======== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Describe.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Describe.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Describe.java` - * :java-better-explain:`Describe.rst` - diff --git a/source/java/DoWhileRollaDie.rst b/source/java/DoWhileRollaDie.rst deleted file mode 100644 index b06bae67..00000000 --- a/source/java/DoWhileRollaDie.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Do While Rolla Die -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/DoWhileRollaDie.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/DoWhileRollaDie.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`DoWhileRollaDie.java` - * :java-better-explain:`DoWhileRollaDie.rst` - diff --git a/source/java/EmptyStatement.rst b/source/java/EmptyStatement.rst deleted file mode 100644 index 2ef7d781..00000000 --- a/source/java/EmptyStatement.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Empty Statement -=============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/EmptyStatement.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/EmptyStatement.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`EmptyStatement.java` - * :java-better-explain:`EmptyStatement.rst` - diff --git a/source/java/EnhancedForStatement.rst b/source/java/EnhancedForStatement.rst deleted file mode 100644 index 8052a64f..00000000 --- a/source/java/EnhancedForStatement.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Enhanced For Statement -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/EnhancedForStatement.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/EnhancedForStatement.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`EnhancedForStatement.java` - * :java-better-explain:`EnhancedForStatement.rst` - diff --git a/source/java/EqualityStrings.rst b/source/java/EqualityStrings.rst deleted file mode 100644 index 90994e50..00000000 --- a/source/java/EqualityStrings.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Example 8 - Equality Strings -============================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/EqualityStrings.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/EqualityStrings.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`EqualityStrings.java` - * :java-better-explain:`EqualityStrings.rst` - diff --git a/source/java/EqualsMethod.rst b/source/java/EqualsMethod.rst deleted file mode 100644 index f8aae567..00000000 --- a/source/java/EqualsMethod.rst +++ /dev/null @@ -1,34 +0,0 @@ -============= -Equals Method -============= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/EqualsMethod.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/EqualsMethod.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`EqualsMethod.java` - * :java-better-explain:`EqualsMethod.rst` - diff --git a/source/java/ExplicitIterable.rst b/source/java/ExplicitIterable.rst deleted file mode 100644 index fa51ffe1..00000000 --- a/source/java/ExplicitIterable.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Explicit Iterable -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ExplicitIterable.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ExplicitIterable.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ExplicitIterable.java` - * :java-better-explain:`ExplicitIterable.rst` - diff --git a/source/java/ExplicitIterableWhileLoop.rst b/source/java/ExplicitIterableWhileLoop.rst deleted file mode 100644 index 0fd366b0..00000000 --- a/source/java/ExplicitIterableWhileLoop.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Explicit Iterable While Loop -============================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ExplicitIterableWhileLoop.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ExplicitIterableWhileLoop.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ExplicitIterableWhileLoop.java` - * :java-better-explain:`ExplicitIterableWhileLoop.rst` - diff --git a/source/java/FieldAccess.rst b/source/java/FieldAccess.rst deleted file mode 100644 index 6c7e1680..00000000 --- a/source/java/FieldAccess.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Field Access -============ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/FieldAccess.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/FieldAccess.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`FieldAccess.java` - * :java-better-explain:`FieldAccess.rst` - diff --git a/source/java/FieldDeclarations.rst b/source/java/FieldDeclarations.rst deleted file mode 100644 index d6562c3c..00000000 --- a/source/java/FieldDeclarations.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Field Declarations -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/FieldDeclarations.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/FieldDeclarations.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`FieldDeclarations.java` - * :java-better-explain:`FieldDeclarations.rst` - diff --git a/source/java/FieldInitializers.rst b/source/java/FieldInitializers.rst deleted file mode 100644 index a746f3e9..00000000 --- a/source/java/FieldInitializers.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Field Initializers -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/FieldInitializers.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/FieldInitializers.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`FieldInitializers.java` - * :java-better-explain:`FieldInitializers.rst` - diff --git a/source/java/FloatingPointFactorial.rst b/source/java/FloatingPointFactorial.rst deleted file mode 100644 index d9e46792..00000000 --- a/source/java/FloatingPointFactorial.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================== -Floating Point Factorial -======================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/FloatingPointFactorial.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/FloatingPointFactorial.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`FloatingPointFactorial.java` - * :java-better-explain:`FloatingPointFactorial.rst` - diff --git a/source/java/ForStatementIterable.rst b/source/java/ForStatementIterable.rst deleted file mode 100644 index 27914476..00000000 --- a/source/java/ForStatementIterable.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -For Statement Iterable -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ForStatementIterable.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ForStatementIterable.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ForStatementIterable.java` - * :java-better-explain:`ForStatementIterable.rst` - diff --git a/source/java/FormattingDateAndTime.rst b/source/java/FormattingDateAndTime.rst deleted file mode 100644 index 1cdb0260..00000000 --- a/source/java/FormattingDateAndTime.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================== -Formatting Date And Time -======================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/FormattingDateAndTime.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/FormattingDateAndTime.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`FormattingDateAndTime.java` - * :java-better-explain:`FormattingDateAndTime.rst` - diff --git a/source/java/GaussianPseudoRandom.rst b/source/java/GaussianPseudoRandom.rst deleted file mode 100644 index b083431c..00000000 --- a/source/java/GaussianPseudoRandom.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Gaussian Pseudo Random -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GaussianPseudoRandom.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GaussianPseudoRandom.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GaussianPseudoRandom.java` - * :java-better-explain:`GaussianPseudoRandom.rst` - diff --git a/source/java/GenericArrayLists.rst b/source/java/GenericArrayLists.rst deleted file mode 100644 index 2cd6075e..00000000 --- a/source/java/GenericArrayLists.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Generic Array Lists -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericArrayLists.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericArrayLists.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericArrayLists.java` - * :java-better-explain:`GenericArrayLists.rst` - diff --git a/source/java/GenericClassLogging.rst b/source/java/GenericClassLogging.rst deleted file mode 100644 index d87d8dfd..00000000 --- a/source/java/GenericClassLogging.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Generic Class Logging -===================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericClassLogging.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericClassLogging.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericClassLogging.java` - * :java-better-explain:`GenericClassLogging.rst` - diff --git a/source/java/GenericClassType.rst b/source/java/GenericClassType.rst deleted file mode 100644 index d2e4144d..00000000 --- a/source/java/GenericClassType.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Generic Class Type -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericClassType.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericClassType.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericClassType.java` - * :java-better-explain:`GenericClassType.rst` - diff --git a/source/java/GenericInterfaceFunction.rst b/source/java/GenericInterfaceFunction.rst deleted file mode 100644 index 5f896027..00000000 --- a/source/java/GenericInterfaceFunction.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Generic Interface Function -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericInterfaceFunction.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericInterfaceFunction.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericInterfaceFunction.java` - * :java-better-explain:`GenericInterfaceFunction.rst` - diff --git a/source/java/GenericLinkedList.rst b/source/java/GenericLinkedList.rst deleted file mode 100644 index 07dc19f8..00000000 --- a/source/java/GenericLinkedList.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Generic Linked List -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericLinkedList.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericLinkedList.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericLinkedList.java` - * :java-better-explain:`GenericLinkedList.rst` - diff --git a/source/java/GenericList.rst b/source/java/GenericList.rst deleted file mode 100644 index 6b468812..00000000 --- a/source/java/GenericList.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Generic List -============ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericList.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericList.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericList.java` - * :java-better-explain:`GenericList.rst` - diff --git a/source/java/GenericMethodGenericClass.rst b/source/java/GenericMethodGenericClass.rst deleted file mode 100644 index 5fdf7bce..00000000 --- a/source/java/GenericMethodGenericClass.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Generic Method Generic Class -============================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericMethodGenericClass.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericMethodGenericClass.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericMethodGenericClass.java` - * :java-better-explain:`GenericMethodGenericClass.rst` - diff --git a/source/java/GenericQuickSort.rst b/source/java/GenericQuickSort.rst deleted file mode 100644 index 51669888..00000000 --- a/source/java/GenericQuickSort.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Generic Quick Sort -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericQuickSort.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericQuickSort.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericQuickSort.java` - * :java-better-explain:`GenericQuickSort.rst` - diff --git a/source/java/GenericQuicksortComparable.rst b/source/java/GenericQuicksortComparable.rst deleted file mode 100644 index 1c37c405..00000000 --- a/source/java/GenericQuicksortComparable.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Generic Quicksort Comparable -============================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericQuicksortComparable.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericQuicksortComparable.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericQuicksortComparable.java` - * :java-better-explain:`GenericQuicksortComparable.rst` - diff --git a/source/java/GenericsLimitation.rst b/source/java/GenericsLimitation.rst deleted file mode 100644 index 19623cdf..00000000 --- a/source/java/GenericsLimitation.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Generics Limitation -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/GenericsLimitation.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/GenericsLimitation.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`GenericsLimitation.java` - * :java-better-explain:`GenericsLimitation.rst` - diff --git a/source/java/HelloUnicode.rst b/source/java/HelloUnicode.rst deleted file mode 100644 index 44db5af4..00000000 --- a/source/java/HelloUnicode.rst +++ /dev/null @@ -1,34 +0,0 @@ -============= -Hello Unicode -============= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Describe.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Describe.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Describe.java` - * :java-better-explain:`Describe.rst` - diff --git a/source/java/HelloWorld.rst b/source/java/HelloWorld.rst deleted file mode 100644 index c6ea7fc4..00000000 --- a/source/java/HelloWorld.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Hello World -=========== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/HelloWorld.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/HelloWorld.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`HelloWorld.java` - * :java-better-explain:`HelloWorld.rst` - diff --git a/source/java/IfTest.rst b/source/java/IfTest.rst deleted file mode 100644 index 369d7f36..00000000 --- a/source/java/IfTest.rst +++ /dev/null @@ -1,34 +0,0 @@ -======= -If Test -======= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/IfTest.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/IfTest.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`IfTest.java` - * :java-better-explain:`IfTest.rst` - diff --git a/source/java/InefficientReplacement.rst b/source/java/InefficientReplacement.rst deleted file mode 100644 index 4a9faf6f..00000000 --- a/source/java/InefficientReplacement.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Inefficient Replacement -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/InefficientReplacement.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/InefficientReplacement.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`InefficientReplacement.java` - * :java-better-explain:`InefficientReplacement.rst` - diff --git a/source/java/InitializedArray.rst b/source/java/InitializedArray.rst deleted file mode 100644 index fe485146..00000000 --- a/source/java/InitializedArray.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Initialized Array -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/InitializedArray.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/InitializedArray.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`InitializedArray.java` - * :java-better-explain:`InitializedArray.rst` - diff --git a/source/java/InnerObjects.rst b/source/java/InnerObjects.rst deleted file mode 100644 index 9ea4a858..00000000 --- a/source/java/InnerObjects.rst +++ /dev/null @@ -1,34 +0,0 @@ -============= -Inner Objects -============= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/InnerObjects.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/InnerObjects.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`InnerObjects.java` - * :java-better-explain:`InnerObjects.rst` - diff --git a/source/java/InputOutputExamples.rst b/source/java/InputOutputExamples.rst deleted file mode 100644 index 7bae6b67..00000000 --- a/source/java/InputOutputExamples.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Input Output Examples -===================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/InputOutputExamples.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/InputOutputExamples.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`InputOutputExamples.java` - * :java-better-explain:`InputOutputExamples.rst` - diff --git a/source/java/IntegerComparator.rst b/source/java/IntegerComparator.rst deleted file mode 100644 index eae86919..00000000 --- a/source/java/IntegerComparator.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Integer Comparator -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/IntegerComparator.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/IntegerComparator.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`IntegerComparator.java` - * :java-better-explain:`IntegerComparator.rst` - diff --git a/source/java/InternalPipes.rst b/source/java/InternalPipes.rst deleted file mode 100644 index 8a76e16c..00000000 --- a/source/java/InternalPipes.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Internal Pipes -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/InternalPipes.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/InternalPipes.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`InternalPipes.java` - * :java-better-explain:`InternalPipes.rst` - diff --git a/source/java/IterationOverIterable.rst b/source/java/IterationOverIterable.rst deleted file mode 100644 index 0734ae2e..00000000 --- a/source/java/IterationOverIterable.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Iteration Over Iterable -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/IterationOverIterable.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/IterationOverIterable.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`IterationOverIterable.java` - * :java-better-explain:`IterationOverIterable.rst` - diff --git a/source/java/IteratorAnonymous.rst b/source/java/IteratorAnonymous.rst deleted file mode 100644 index c4d10292..00000000 --- a/source/java/IteratorAnonymous.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Iterator Anonymous -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/IteratorAnonymous.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/IteratorAnonymous.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`IteratorAnonymous.java` - * :java-better-explain:`IteratorAnonymous.rst` - diff --git a/source/java/JavaFiveFeatures.rst b/source/java/JavaFiveFeatures.rst deleted file mode 100644 index 923b0e91..00000000 --- a/source/java/JavaFiveFeatures.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -JavaFive Features -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/JavaFiveFeatures.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/JavaFiveFeatures.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`JavaFiveFeatures.java` - * :java-better-explain:`JavaFiveFeatures.rst` - diff --git a/source/java/Layout.rst b/source/java/Layout.rst deleted file mode 100644 index 96ff399c..00000000 --- a/source/java/Layout.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Example 2 - Layout -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Layout.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Layout.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Layout.java` - * :java-better-explain:`Layout.rst` - diff --git a/source/java/Lexicographic.rst b/source/java/Lexicographic.rst deleted file mode 100644 index b3ee33ca..00000000 --- a/source/java/Lexicographic.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Example 11 - Lexicographic -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Lexicographic.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Lexicographic.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Lexicographic.java` - * :java-better-explain:`Lexicographic.rst` - diff --git a/source/java/LinkedHashSetRemoveDuplicates.rst b/source/java/LinkedHashSetRemoveDuplicates.rst deleted file mode 100644 index 16c8bf4c..00000000 --- a/source/java/LinkedHashSetRemoveDuplicates.rst +++ /dev/null @@ -1,34 +0,0 @@ -================================= -Linked Hash Set Remove Duplicates -================================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/LinkedHashSetRemoveDuplicates.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/LinkedHashSetRemoveDuplicates.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`LinkedHashSetRemoveDuplicates.java` - * :java-better-explain:`LinkedHashSetRemoveDuplicates.rst` - diff --git a/source/java/LocalInnerClassInterator.rst b/source/java/LocalInnerClassInterator.rst deleted file mode 100644 index 487d1192..00000000 --- a/source/java/LocalInnerClassInterator.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========================== -Local Inner Class Interator -=========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/LocalInnerClassInterator.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/LocalInnerClassInterator.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`LocalInnerClassInterator.java` - * :java-better-explain:`LocalInnerClassInterator.rst` - diff --git a/source/java/LocaleSpecificDate.rst b/source/java/LocaleSpecificDate.rst deleted file mode 100644 index c3c9fe64..00000000 --- a/source/java/LocaleSpecificDate.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Locale Specific Date -==================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/LocaleSpecificDate.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/LocaleSpecificDate.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`LocaleSpecificDate.java` - * :java-better-explain:`LocaleSpecificDate.rst` - diff --git a/source/java/LocaleSpecificNumbers.rst b/source/java/LocaleSpecificNumbers.rst deleted file mode 100644 index d91b131f..00000000 --- a/source/java/LocaleSpecificNumbers.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Locale Specific Numbers -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/LocaleSpecificNumbers.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/LocaleSpecificNumbers.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`LocaleSpecificNumbers.java` - * :java-better-explain:`LocaleSpecificNumbers.rst` - diff --git a/source/java/LogicalOperators.rst b/source/java/LogicalOperators.rst deleted file mode 100644 index d710a917..00000000 --- a/source/java/LogicalOperators.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Logical Operators -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/LogicalOperators.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/LogicalOperators.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`LogicalOperators.java` - * :java-better-explain:`LogicalOperators.rst` - diff --git a/source/java/MathematicalFunctions.rst b/source/java/MathematicalFunctions.rst deleted file mode 100644 index 11bc5ee1..00000000 --- a/source/java/MathematicalFunctions.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Mathematical Functions -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MathematicalFunctions.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MathematicalFunctions.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MathematicalFunctions.java` - * :java-better-explain:`MathematicalFunctions.rst` - diff --git a/source/java/MemberAccessModifiers.rst b/source/java/MemberAccessModifiers.rst deleted file mode 100644 index d5c5555d..00000000 --- a/source/java/MemberAccessModifiers.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Member Access Modifiers -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MemberAccessModifiers.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MemberAccessModifiers.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MemberAccessModifiers.java` - * :java-better-explain:`MemberAccessModifiers.rst` - diff --git a/source/java/MemberClasses.rst b/source/java/MemberClasses.rst deleted file mode 100644 index 28565dad..00000000 --- a/source/java/MemberClasses.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Member Classes -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MemberClasses.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MemberClasses.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MemberClasses.java` - * :java-better-explain:`MemberClasses.rst` - diff --git a/source/java/MethodNameOverloading.rst b/source/java/MethodNameOverloading.rst deleted file mode 100644 index b06a0b86..00000000 --- a/source/java/MethodNameOverloading.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Method Name Overloading -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MethodNameOverloading.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MethodNameOverloading.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MethodNameOverloading.java` - * :java-better-explain:`MethodNameOverloading.rst` - diff --git a/source/java/MethodOverloadingHiding.rst b/source/java/MethodOverloadingHiding.rst deleted file mode 100644 index 602d6268..00000000 --- a/source/java/MethodOverloadingHiding.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================= -Method Overloading Hiding -========================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MethodOverloadingHiding.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MethodOverloadingHiding.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MethodOverloadingHiding.java` - * :java-better-explain:`MethodOverloadingHiding.rst` - diff --git a/source/java/MethodOverloadingParameterArray.rst b/source/java/MethodOverloadingParameterArray.rst deleted file mode 100644 index a1927e3d..00000000 --- a/source/java/MethodOverloadingParameterArray.rst +++ /dev/null @@ -1,34 +0,0 @@ -================================== -Method Overloading Parameter Array -================================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MethodOverloadingParameterArray.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MethodOverloadingParameterArray.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MethodOverloadingParameterArray.java` - * :java-better-explain:`MethodOverloadingParameterArray.rst` - diff --git a/source/java/MethodReturningIterable.rst b/source/java/MethodReturningIterable.rst deleted file mode 100644 index 5709c4a4..00000000 --- a/source/java/MethodReturningIterable.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================= -Method Returning Iterable -========================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MethodReturningIterable.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MethodReturningIterable.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MethodReturningIterable.java` - * :java-better-explain:`MethodReturningIterable.rst` - diff --git a/source/java/MultiDimensionalArray.rst b/source/java/MultiDimensionalArray.rst deleted file mode 100644 index 9ac5a523..00000000 --- a/source/java/MultiDimensionalArray.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Multi Dimensional Array -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MultiDimensionalArray.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MultiDimensionalArray.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MultiDimensionalArray.java` - * :java-better-explain:`MultiDimensionalArray.rst` - diff --git a/source/java/MultipleThreads.rst b/source/java/MultipleThreads.rst deleted file mode 100644 index f019aff1..00000000 --- a/source/java/MultipleThreads.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Multiple Threads -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MultipleThreads.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MultipleThreads.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MultipleThreads.java` - * :java-better-explain:`MultipleThreads.rst` - diff --git a/source/java/MutualExclusion.rst b/source/java/MutualExclusion.rst deleted file mode 100644 index 1f9c636f..00000000 --- a/source/java/MutualExclusion.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Mutual Exclusion -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/MutualExclusion.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/MutualExclusion.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`MutualExclusion.java` - * :java-better-explain:`MutualExclusion.rst` - diff --git a/source/java/NestedForLoops.rst b/source/java/NestedForLoops.rst deleted file mode 100644 index 31a72ed8..00000000 --- a/source/java/NestedForLoops.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Nested For Loops -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/NestedForLoops.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/NestedForLoops.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`NestedForLoops.java` - * :java-better-explain:`NestedForLoops.rst` - diff --git a/source/java/NonGenericArrayList.rst b/source/java/NonGenericArrayList.rst deleted file mode 100644 index e52e35b3..00000000 --- a/source/java/NonGenericArrayList.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Non Generic Array List -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/NonGenericArrayList.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/NonGenericArrayList.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`NonGenericArrayList.java` - * :java-better-explain:`NonGenericArrayList.rst` - diff --git a/source/java/ObjectCreation.rst b/source/java/ObjectCreation.rst deleted file mode 100644 index fe58fbd1..00000000 --- a/source/java/ObjectCreation.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Object Creation -=============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ObjectCreation.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ObjectCreation.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ObjectCreation.java` - * :java-better-explain:`ObjectCreation.rst` - diff --git a/source/java/ObjectsAndClasses.rst b/source/java/ObjectsAndClasses.rst deleted file mode 100644 index 48be5f9e..00000000 --- a/source/java/ObjectsAndClasses.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Objects And Classes -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ObjectsAndClasses.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ObjectsAndClasses.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ObjectsAndClasses.java` - * :java-better-explain:`ObjectsAndClasses.rst` - diff --git a/source/java/ObjectsWithMultipleFields.rst b/source/java/ObjectsWithMultipleFields.rst deleted file mode 100644 index 3942e696..00000000 --- a/source/java/ObjectsWithMultipleFields.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Objects With Multiple Fields -============================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ObjectsWithMultipleFields.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ObjectsWithMultipleFields.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ObjectsWithMultipleFields.java` - * :java-better-explain:`ObjectsWithMultipleFields.rst` - diff --git a/source/java/ObtainedSubMap.rst b/source/java/ObtainedSubMap.rst deleted file mode 100644 index 86603010..00000000 --- a/source/java/ObtainedSubMap.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Obtained Sub Map -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ObtainedSubMap.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ObtainedSubMap.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ObtainedSubMap.java` - * :java-better-explain:`ObtainedSubMap.rst` - diff --git a/source/java/OneDimensionalArray.rst b/source/java/OneDimensionalArray.rst deleted file mode 100644 index 2b3170b6..00000000 --- a/source/java/OneDimensionalArray.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -One Dimensional Array -===================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/OneDimensionalArray.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/OneDimensionalArray.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`OneDimensionalArray.java` - * :java-better-explain:`OneDimensionalArray.rst` - diff --git a/source/java/OutputBuffering.rst b/source/java/OutputBuffering.rst deleted file mode 100644 index 18f3bee1..00000000 --- a/source/java/OutputBuffering.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Output Buffering -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/OutputBuffering.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/OutputBuffering.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`OutputBuffering.java` - * :java-better-explain:`OutputBuffering.rst` - diff --git a/source/java/PaddingString.rst b/source/java/PaddingString.rst deleted file mode 100644 index cbc5983c..00000000 --- a/source/java/PaddingString.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Padding String -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/PaddingString.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/PaddingString.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`PaddingString.java` - * :java-better-explain:`PaddingString.rst` - diff --git a/source/java/ParameterPassing.rst b/source/java/ParameterPassing.rst deleted file mode 100644 index a5d85f41..00000000 --- a/source/java/ParameterPassing.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Parameter Passing -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ParameterPassing.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ParameterPassing.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ParameterPassing.java` - * :java-better-explain:`ParameterPassing.rst` - diff --git a/source/java/Point.rst b/source/java/Point.rst deleted file mode 100644 index 6728cc9a..00000000 --- a/source/java/Point.rst +++ /dev/null @@ -1,34 +0,0 @@ -===== -Point -===== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Point.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Point.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Point.java` - * :java-better-explain:`Point.rst` - diff --git a/source/java/PrintHTMLTable.rst b/source/java/PrintHTMLTable.rst deleted file mode 100644 index 506fad9f..00000000 --- a/source/java/PrintHTMLTable.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Print HTML Table -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/PrintHTMLTable.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/PrintHTMLTable.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`PrintHTMLTable.java` - * :java-better-explain:`PrintHTMLTable.rst` - diff --git a/source/java/PrintingNumbers.rst b/source/java/PrintingNumbers.rst deleted file mode 100644 index a871290b..00000000 --- a/source/java/PrintingNumbers.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Printing Numbers -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/PrintingNumbers.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/PrintingNumbers.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`PrintingNumbers.java` - * :java-better-explain:`PrintingNumbers.rst` - diff --git a/source/java/PrivateMemberAccess.rst b/source/java/PrivateMemberAccess.rst deleted file mode 100644 index 221a4ff3..00000000 --- a/source/java/PrivateMemberAccess.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Private Member Access -===================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/PrivateMemberAccess.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/PrivateMemberAccess.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`PrivateMemberAccess.java` - * :java-better-explain:`PrivateMemberAccess.rst` - diff --git a/source/java/ProducerConsumer.rst b/source/java/ProducerConsumer.rst deleted file mode 100644 index 339ca78d..00000000 --- a/source/java/ProducerConsumer.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Producer Consumer -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ProducerConsumer.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ProducerConsumer.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ProducerConsumer.java` - * :java-better-explain:`ProducerConsumer.rst` - diff --git a/source/java/RandomAccessReads.rst b/source/java/RandomAccessReads.rst deleted file mode 100644 index c6100538..00000000 --- a/source/java/RandomAccessReads.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Random Access Reads -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/RandomAccessReads.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/RandomAccessReads.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`RandomAccessReads.java` - * :java-better-explain:`RandomAccessReads.rst` - diff --git a/source/java/ReadingNumbers.rst b/source/java/ReadingNumbers.rst deleted file mode 100644 index 7d5789b0..00000000 --- a/source/java/ReadingNumbers.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Reading Numbers -=============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReadingNumbers.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReadingNumbers.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReadingNumbers.java` - * :java-better-explain:`ReadingNumbers.rst` - diff --git a/source/java/ReadingNumbersLineByLine.rst b/source/java/ReadingNumbersLineByLine.rst deleted file mode 100644 index de1c3f54..00000000 --- a/source/java/ReadingNumbersLineByLine.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Reading Numbers Line By Line -============================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReadingNumbersLineByLine.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReadingNumbersLineByLine.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReadingNumbersLineByLine.java` - * :java-better-explain:`ReadingNumbersLineByLine.rst` - diff --git a/source/java/ReadingPrintingDirHierarchy.rst b/source/java/ReadingPrintingDirHierarchy.rst deleted file mode 100644 index b6164534..00000000 --- a/source/java/ReadingPrintingDirHierarchy.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================== -Reading Printing Dir Hierarchy -============================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReadingPrintingDirHierarchy.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReadingPrintingDirHierarchy.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReadingPrintingDirHierarchy.java` - * :java-better-explain:`ReadingPrintingDirHierarchy.rst` - diff --git a/source/java/ReflectionPublicMethods.rst b/source/java/ReflectionPublicMethods.rst deleted file mode 100644 index 3f364838..00000000 --- a/source/java/ReflectionPublicMethods.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================= -Reflection Public Methods -========================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReflectionPublicMethods.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReflectionPublicMethods.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReflectionPublicMethods.java` - * :java-better-explain:`ReflectionPublicMethods.rst` - diff --git a/source/java/ReflectiveAccessToField.rst b/source/java/ReflectiveAccessToField.rst deleted file mode 100644 index 6975626a..00000000 --- a/source/java/ReflectiveAccessToField.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Reflective Access To Field -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReflectiveAccessToField.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReflectiveAccessToField.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReflectiveAccessToField.java` - * :java-better-explain:`ReflectiveAccessToField.rst` - diff --git a/source/java/ReflectiveCreation.rst b/source/java/ReflectiveCreation.rst deleted file mode 100644 index 79f3d23b..00000000 --- a/source/java/ReflectiveCreation.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Reflective Creation -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReflectiveCreation.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReflectiveCreation.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReflectiveCreation.java` - * :java-better-explain:`ReflectiveCreation.rst` - diff --git a/source/java/ReflectiveInspection.rst b/source/java/ReflectiveInspection.rst deleted file mode 100644 index cf7683c1..00000000 --- a/source/java/ReflectiveInspection.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Reflective Inspection -===================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReflectiveInspection.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReflectiveInspection.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReflectiveInspection.java` - * :java-better-explain:`ReflectiveInspection.rst` - diff --git a/source/java/ReflectiveObjectCreation.rst b/source/java/ReflectiveObjectCreation.rst deleted file mode 100644 index 3c2c9470..00000000 --- a/source/java/ReflectiveObjectCreation.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Reflective Object Creation -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReflectiveObjectCreation.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReflectiveObjectCreation.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReflectiveObjectCreation.java` - * :java-better-explain:`ReflectiveObjectCreation.rst` - diff --git a/source/java/ReflectiveRetrieval.rst b/source/java/ReflectiveRetrieval.rst deleted file mode 100644 index 64d3bb8a..00000000 --- a/source/java/ReflectiveRetrieval.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Reflective Retrieval -==================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReflectiveRetrieval.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReflectiveRetrieval.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReflectiveRetrieval.java` - * :java-better-explain:`ReflectiveRetrieval.rst` - diff --git a/source/java/ReplaceOccurances.rst b/source/java/ReplaceOccurances.rst deleted file mode 100644 index 7722e4c7..00000000 --- a/source/java/ReplaceOccurances.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Replace Occurances -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ReplaceOccurances.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ReplaceOccurances.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ReplaceOccurances.java` - * :java-better-explain:`ReplaceOccurances.rst` - diff --git a/source/java/RepresentingWeekdays.rst b/source/java/RepresentingWeekdays.rst deleted file mode 100644 index 0c249191..00000000 --- a/source/java/RepresentingWeekdays.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Representing Weekdays -===================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/RepresentingWeekdays.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/RepresentingWeekdays.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`RepresentingWeekdays.java` - * :java-better-explain:`RepresentingWeekdays.rst` - diff --git a/source/java/Scope.rst b/source/java/Scope.rst deleted file mode 100644 index 641ec190..00000000 --- a/source/java/Scope.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Example 7 - Scope -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Scope.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Scope.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Scope.java` - * :java-better-explain:`Scope.rst` - diff --git a/source/java/SequenceIfElse.rst b/source/java/SequenceIfElse.rst deleted file mode 100644 index 168b56e8..00000000 --- a/source/java/SequenceIfElse.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Sequence If Else -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SequenceIfElse.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SequenceIfElse.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SequenceIfElse.java` - * :java-better-explain:`SequenceIfElse.rst` - diff --git a/source/java/SerializationDistinctObject.rst b/source/java/SerializationDistinctObject.rst deleted file mode 100644 index f76c29a8..00000000 --- a/source/java/SerializationDistinctObject.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================= -Serialization Distinct Object -============================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SerializationDistinctObject.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SerializationDistinctObject.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SerializationDistinctObject.java` - * :java-better-explain:`SerializationDistinctObject.rst` - diff --git a/source/java/SerializationSameObject.rst b/source/java/SerializationSameObject.rst deleted file mode 100644 index 71b2e425..00000000 --- a/source/java/SerializationSameObject.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================= -Serialization Same Object -========================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SerializationSameObject.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SerializationSameObject.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SerializationSameObject.java` - * :java-better-explain:`SerializationSameObject.rst` - diff --git a/source/java/SetMembership.rst b/source/java/SetMembership.rst deleted file mode 100644 index 0aa77873..00000000 --- a/source/java/SetMembership.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Set Membership -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SetMembership.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SetMembership.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SetMembership.java` - * :java-better-explain:`SetMembership.rst` - diff --git a/source/java/SetsKeysinHashMap.rst b/source/java/SetsKeysinHashMap.rst deleted file mode 100644 index c5e181fe..00000000 --- a/source/java/SetsKeysinHashMap.rst +++ /dev/null @@ -1,35 +0,0 @@ -===================== -Sets Keys in Hash Map -===================== - -Question -======== - -Demonstrate the Set types as keys in Hashmap. - -Solution -======== - -.. literalinclude:: ../../languages/java/SetsKeysinHashMap.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SetsKeysinHashMap.java - :language: java - :codesite: ideone - -Explanation -=========== - -Sets can be used as keys in Hashmap. The example demonstrates this feature. - - - - - - -.. seealso:: - - * :java-suggest-improve:`SetsKeysinHashMap.java` - * :java-better-explain:`SetsKeysinHashMap.rst` - diff --git a/source/java/SeveralFieldsSameName.rst b/source/java/SeveralFieldsSameName.rst deleted file mode 100644 index ff759330..00000000 --- a/source/java/SeveralFieldsSameName.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================== -Several Fields Same Name -======================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SeveralFieldsSameName.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SeveralFieldsSameName.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SeveralFieldsSameName.java` - * :java-better-explain:`SeveralFieldsSameName.rst` - diff --git a/source/java/SingleIfElse.rst b/source/java/SingleIfElse.rst deleted file mode 100644 index 7b69fb7f..00000000 --- a/source/java/SingleIfElse.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Single If Else -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SingleIfElse.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SingleIfElse.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SingleIfElse.java` - * :java-better-explain:`SingleIfElse.rst` - diff --git a/source/java/SocketCommunication.rst b/source/java/SocketCommunication.rst deleted file mode 100644 index f02b8f89..00000000 --- a/source/java/SocketCommunication.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Socket Communication -==================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SocketCommunication.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SocketCommunication.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SocketCommunication.java` - * :java-better-explain:`SocketCommunication.rst` - diff --git a/source/java/SpecifyingOutputEncoding.rst b/source/java/SpecifyingOutputEncoding.rst deleted file mode 100644 index 96bdf8ac..00000000 --- a/source/java/SpecifyingOutputEncoding.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Specifying Output Encoding -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SpecifyingOutputEncoding.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SpecifyingOutputEncoding.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SpecifyingOutputEncoding.java` - * :java-better-explain:`SpecifyingOutputEncoding.rst` - diff --git a/source/java/StoringResultsDatabase.rst b/source/java/StoringResultsDatabase.rst deleted file mode 100644 index cdab1d23..00000000 --- a/source/java/StoringResultsDatabase.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================== -Storing Results Database -======================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/StoringResultsDatabase.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/StoringResultsDatabase.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`StoringResultsDatabase.java` - * :java-better-explain:`StoringResultsDatabase.rst` - diff --git a/source/java/StringArrayFile.rst b/source/java/StringArrayFile.rst deleted file mode 100644 index 0c7367b3..00000000 --- a/source/java/StringArrayFile.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -String Array File -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/StringArrayFile.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/StringArrayFile.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`StringArrayFile.java` - * :java-better-explain:`StringArrayFile.rst` - diff --git a/source/java/StringComparator.rst b/source/java/StringComparator.rst deleted file mode 100644 index 4718462f..00000000 --- a/source/java/StringComparator.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -String Comparator -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/StringComparator.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/StringComparator.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`StringComparator.java` - * :java-better-explain:`StringComparator.rst` - diff --git a/source/java/StringFromCharArray.rst b/source/java/StringFromCharArray.rst deleted file mode 100644 index 433109ca..00000000 --- a/source/java/StringFromCharArray.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -String From Char Array -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/StringFromCharArray.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/StringFromCharArray.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`StringFromCharArray.java` - * :java-better-explain:`StringFromCharArray.rst` - diff --git a/source/java/SubtypeRelations.rst b/source/java/SubtypeRelations.rst deleted file mode 100644 index fa489c7e..00000000 --- a/source/java/SubtypeRelations.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Subtype Relations -================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SubtypeRelations.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SubtypeRelations.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SubtypeRelations.java` - * :java-better-explain:`SubtypeRelations.rst` - diff --git a/source/java/SuperclassConstructor.rst b/source/java/SuperclassConstructor.rst deleted file mode 100644 index 49001ba2..00000000 --- a/source/java/SuperclassConstructor.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Superclass Constructor -====================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SuperclassConstructor.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SuperclassConstructor.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SuperclassConstructor.java` - * :java-better-explain:`SuperclassConstructor.rst` - diff --git a/source/java/SwitchOnEnum.rst b/source/java/SwitchOnEnum.rst deleted file mode 100644 index 65c1fe0b..00000000 --- a/source/java/SwitchOnEnum.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Switch On Enum -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SwitchOnEnum.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SwitchOnEnum.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SwitchOnEnum.java` - * :java-better-explain:`SwitchOnEnum.rst` - diff --git a/source/java/SwitchStatement.rst b/source/java/SwitchStatement.rst deleted file mode 100644 index 84572731..00000000 --- a/source/java/SwitchStatement.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Switch Statement -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SwitchStatement.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SwitchStatement.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SwitchStatement.java` - * :java-better-explain:`SwitchStatement.rst` - diff --git a/source/java/SwitchStatementStrings.rst b/source/java/SwitchStatementStrings.rst deleted file mode 100644 index c7aa3440..00000000 --- a/source/java/SwitchStatementStrings.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================== -Switch Statement Strings -======================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SwitchStatementStrings.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SwitchStatementStrings.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SwitchStatementStrings.java` - * :java-better-explain:`SwitchStatementStrings.rst` - diff --git a/source/java/SynchronizedMethods.rst b/source/java/SynchronizedMethods.rst deleted file mode 100644 index 64e8b965..00000000 --- a/source/java/SynchronizedMethods.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Synchronized Methods -==================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/SynchronizedMethods.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/SynchronizedMethods.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`SynchronizedMethods.java` - * :java-better-explain:`SynchronizedMethods.rst` - diff --git a/source/java/ThreeInterfaces.rst b/source/java/ThreeInterfaces.rst deleted file mode 100644 index 1ae5df6a..00000000 --- a/source/java/ThreeInterfaces.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Three Interfaces -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ThreeInterfaces.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ThreeInterfaces.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ThreeInterfaces.java` - * :java-better-explain:`ThreeInterfaces.rst` - diff --git a/source/java/ThrowingExceptionFailure.rst b/source/java/ThrowingExceptionFailure.rst deleted file mode 100644 index 1e4c991e..00000000 --- a/source/java/ThrowingExceptionFailure.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Throwing Exception Failure -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ThrowingExceptionFailure.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ThrowingExceptionFailure.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ThrowingExceptionFailure.java` - * :java-better-explain:`ThrowingExceptionFailure.rst` - diff --git a/source/java/TimeComparable.rst b/source/java/TimeComparable.rst deleted file mode 100644 index d93dcaa0..00000000 --- a/source/java/TimeComparable.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Time Comparable -=============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/TimeComparable.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/TimeComparable.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`TimeComparable.java` - * :java-better-explain:`TimeComparable.rst` - diff --git a/source/java/ToString.rst b/source/java/ToString.rst deleted file mode 100644 index 382453e6..00000000 --- a/source/java/ToString.rst +++ /dev/null @@ -1,34 +0,0 @@ -========= -To String -========= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/ToString.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/ToString.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`ToString.java` - * :java-better-explain:`ToString.rst` - diff --git a/source/java/TopLevelClass.rst b/source/java/TopLevelClass.rst deleted file mode 100644 index 1dfb8073..00000000 --- a/source/java/TopLevelClass.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -TopLevel Class -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/TopLevelClass.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/TopLevelClass.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`TopLevelClass.java` - * :java-better-explain:`TopLevelClass.rst` - diff --git a/source/java/TreeSetRange.rst b/source/java/TreeSetRange.rst deleted file mode 100644 index 08b81eb7..00000000 --- a/source/java/TreeSetRange.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Tree Set Range -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/TreeSetRange.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/TreeSetRange.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`TreeSetRange.java` - * :java-better-explain:`TreeSetRange.rst` - diff --git a/source/java/TryCatch.rst b/source/java/TryCatch.rst deleted file mode 100644 index 4c1239f2..00000000 --- a/source/java/TryCatch.rst +++ /dev/null @@ -1,34 +0,0 @@ -========= -Try Catch -========= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/TryCatch.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/TryCatch.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`TryCatch.java` - * :java-better-explain:`TryCatch.rst` - diff --git a/source/java/TryFinally.rst b/source/java/TryFinally.rst deleted file mode 100644 index 5f313460..00000000 --- a/source/java/TryFinally.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Try Finally -=========== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/TryFinally.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/TryFinally.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`TryFinally.java` - * :java-better-explain:`TryFinally.rst` - diff --git a/source/java/TypeErasure.rst b/source/java/TypeErasure.rst deleted file mode 100644 index 8d80206c..00000000 --- a/source/java/TypeErasure.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Type Erasure -============ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/TypeErasure.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/TypeErasure.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`TypeErasure.java` - * :java-better-explain:`TypeErasure.rst` - diff --git a/source/java/TypeParameter.rst b/source/java/TypeParameter.rst deleted file mode 100644 index 902088b1..00000000 --- a/source/java/TypeParameter.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Type Parameter -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/TypeParameter.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/TypeParameter.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`TypeParameter.java` - * :java-better-explain:`TypeParameter.rst` - diff --git a/source/java/UncheckedCast.rst b/source/java/UncheckedCast.rst deleted file mode 100644 index 591af71d..00000000 --- a/source/java/UncheckedCast.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Unchecked Cast -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UncheckedCast.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UncheckedCast.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UncheckedCast.java` - * :java-better-explain:`UncheckedCast.rst` - diff --git a/source/java/UnderstandingCollectionsbinarySearch.rst b/source/java/UnderstandingCollectionsbinarySearch.rst deleted file mode 100644 index e5448228..00000000 --- a/source/java/UnderstandingCollectionsbinarySearch.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================================== -Understanding Collectionsbinary Search -====================================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UnderstandingCollectionsbinarySearch.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UnderstandingCollectionsbinarySearch.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UnderstandingCollectionsbinarySearch.java` - * :java-better-explain:`UnderstandingCollectionsbinarySearch.rst` - diff --git a/source/java/UnderstandingCollectionscopy.rst b/source/java/UnderstandingCollectionscopy.rst deleted file mode 100644 index 71514fcb..00000000 --- a/source/java/UnderstandingCollectionscopy.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================= -Understanding Collectionscopy -============================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UnderstandingCollectionscopy.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UnderstandingCollectionscopy.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UnderstandingCollectionscopy.java` - * :java-better-explain:`UnderstandingCollectionscopy.rst` - diff --git a/source/java/UniqueClassObject.rst b/source/java/UniqueClassObject.rst deleted file mode 100644 index 9f885330..00000000 --- a/source/java/UniqueClassObject.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Unique Class Object -=================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UniqueClassObject.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UniqueClassObject.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UniqueClassObject.java` - * :java-better-explain:`UniqueClassObject.rst` - diff --git a/source/java/UsingAppendableInterface.rst b/source/java/UsingAppendableInterface.rst deleted file mode 100644 index 43091c8f..00000000 --- a/source/java/UsingAppendableInterface.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================== -Using Appendable Interface -========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingAppendableInterface.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingAppendableInterface.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingAppendableInterface.java` - * :java-better-explain:`UsingAppendableInterface.rst` - diff --git a/source/java/UsingBreakToExitLabeled.rst b/source/java/UsingBreakToExitLabeled.rst deleted file mode 100644 index 131a33ef..00000000 --- a/source/java/UsingBreakToExitLabeled.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========================== -Using Break To Exit Labeled -=========================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingBreakToExitLabeled.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingBreakToExitLabeled.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingBreakToExitLabeled.java` - * :java-better-explain:`UsingBreakToExitLabeled.rst` - diff --git a/source/java/UsingBreakToTerminateLoop.rst b/source/java/UsingBreakToTerminateLoop.rst deleted file mode 100644 index 23367560..00000000 --- a/source/java/UsingBreakToTerminateLoop.rst +++ /dev/null @@ -1,33 +0,0 @@ -============================= -Using Break To Terminate Loop -============================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingBreakToTerminateLoop.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingBreakToTerminateLoop.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingBreakToTerminateLoop.java` - * :java-better-explain:`UsingBreakToTerminateLoop.rst` - diff --git a/source/java/UsingContinueStartIteration.rst b/source/java/UsingContinueStartIteration.rst deleted file mode 100644 index 7f571830..00000000 --- a/source/java/UsingContinueStartIteration.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================== -Using Continue Start Iteration -============================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingContinueStartIteration.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingContinueStartIteration.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingContinueStartIteration.java` - * :java-better-explain:`UsingContinueStartIteration.rst` - diff --git a/source/java/UsingCustomAnnotation.rst b/source/java/UsingCustomAnnotation.rst deleted file mode 100644 index 21f8608a..00000000 --- a/source/java/UsingCustomAnnotation.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Using Custom Annotation -======================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingCustomAnnotation.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingCustomAnnotation.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingCustomAnnotation.java` - * :java-better-explain:`UsingCustomAnnotation.rst` - diff --git a/source/java/UsingInterfacesAsTypes.rst b/source/java/UsingInterfacesAsTypes.rst deleted file mode 100644 index e75d34cf..00000000 --- a/source/java/UsingInterfacesAsTypes.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================= -Using Interfaces As Types -========================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingInterfacesAsTypes.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingInterfacesAsTypes.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingInterfacesAsTypes.java` - * :java-better-explain:`UsingInterfacesAsTypes.rst` - diff --git a/source/java/UsingMultidimentionalArrays.rst b/source/java/UsingMultidimentionalArrays.rst deleted file mode 100644 index 8881fc7c..00000000 --- a/source/java/UsingMultidimentionalArrays.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================= -Using Multidimentional Arrays -============================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingMultidimentionalArrays.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingMultidimentionalArrays.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingMultidimentionalArrays.java` - * :java-better-explain:`UsingMultidimentionalArrays.rst` - diff --git a/source/java/UsingReturntoTerminateLoop.rst b/source/java/UsingReturntoTerminateLoop.rst deleted file mode 100644 index ebe6d166..00000000 --- a/source/java/UsingReturntoTerminateLoop.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================= -Using Returnto Terminate Loop -============================= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingReturntoTerminateLoop.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingReturntoTerminateLoop.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingReturntoTerminateLoop.java` - * :java-better-explain:`UsingReturntoTerminateLoop.rst` - diff --git a/source/java/Usingassert.rst b/source/java/Usingassert.rst deleted file mode 100644 index 0675636b..00000000 --- a/source/java/Usingassert.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Usingassert -=========== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Usingassert.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Usingassert.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Usingassert.java` - * :java-better-explain:`Usingassert.rst` - diff --git a/source/java/UsingassertsCheckAlgorithm.rst b/source/java/UsingassertsCheckAlgorithm.rst deleted file mode 100644 index 8d543cab..00000000 --- a/source/java/UsingassertsCheckAlgorithm.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Usingasserts Check Algorithm -============================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingassertsCheckAlgorithm.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingassertsCheckAlgorithm.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingassertsCheckAlgorithm.java` - * :java-better-explain:`UsingassertsCheckAlgorithm.rst` - diff --git a/source/java/Usingthis.rst b/source/java/Usingthis.rst deleted file mode 100644 index d4c36591..00000000 --- a/source/java/Usingthis.rst +++ /dev/null @@ -1,34 +0,0 @@ -========= -Usingthis -========= - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/Usingthis.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/Usingthis.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`Usingthis.java` - * :java-better-explain:`Usingthis.rst` - diff --git a/source/java/UsingthisObject.rst b/source/java/UsingthisObject.rst deleted file mode 100644 index 8b73b6f5..00000000 --- a/source/java/UsingthisObject.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Usingthis Object -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/UsingthisObject.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/UsingthisObject.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`UsingthisObject.java` - * :java-better-explain:`UsingthisObject.rst` - diff --git a/source/java/VariableDeclaration.rst b/source/java/VariableDeclaration.rst deleted file mode 100644 index d88d539b..00000000 --- a/source/java/VariableDeclaration.rst +++ /dev/null @@ -1,34 +0,0 @@ -================================ -Example 6 - Variable Declaration -================================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/VariableDeclaration.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/VariableDeclaration.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`VariableDeclaration.java` - * :java-better-explain:`VariableDeclaration.rst` - diff --git a/source/java/VesselHeirarchy.rst b/source/java/VesselHeirarchy.rst deleted file mode 100644 index cdc297f3..00000000 --- a/source/java/VesselHeirarchy.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Vessel Heirarchy -================ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/VesselHeirarchy.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/VesselHeirarchy.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`VesselHeirarchy.java` - * :java-better-explain:`VesselHeirarchy.rst` - diff --git a/source/java/WeekdayNametoNumberHashMap.rst b/source/java/WeekdayNametoNumberHashMap.rst deleted file mode 100644 index a8a62a73..00000000 --- a/source/java/WeekdayNametoNumberHashMap.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============================== -Weekday Name To Number Hash Map -=============================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/WeekdayNametoNumberHashMap.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/WeekdayNametoNumberHashMap.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`WeekdayNametoNumberHashMap.java` - * :java-better-explain:`WeekdayNametoNumberHashMap.rst` - diff --git a/source/java/WhileLoop.rst b/source/java/WhileLoop.rst deleted file mode 100644 index cc1fd095..00000000 --- a/source/java/WhileLoop.rst +++ /dev/null @@ -1,34 +0,0 @@ -========== -While Loop -========== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/WhileLoop.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/WhileLoop.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`WhileLoop.java` - * :java-better-explain:`WhileLoop.rst` - diff --git a/source/java/WideningNarrowing.rst b/source/java/WideningNarrowing.rst deleted file mode 100644 index 9a1fff4c..00000000 --- a/source/java/WideningNarrowing.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Widening Narrowing -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/WideningNarrowing.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/WideningNarrowing.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`WideningNarrowing.java` - * :java-better-explain:`WideningNarrowing.rst` - diff --git a/source/java/WildcardTypes.rst b/source/java/WildcardTypes.rst deleted file mode 100644 index 9b50c4f9..00000000 --- a/source/java/WildcardTypes.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Wildcard Types -============== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/WildcardTypes.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/WildcardTypes.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`WildcardTypes.java` - * :java-better-explain:`WildcardTypes.rst` - diff --git a/source/java/WorklistAlgorithm.rst b/source/java/WorklistAlgorithm.rst deleted file mode 100644 index 510355f4..00000000 --- a/source/java/WorklistAlgorithm.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Worklist Algorithm -================== - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/WorklistAlgorithm.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/WorklistAlgorithm.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :java-suggest-improve:`WorklistAlgorithm.java` - * :java-better-explain:`WorklistAlgorithm.rst` - diff --git a/source/java/index.rst b/source/java/index.rst deleted file mode 100644 index 293a1f82..00000000 --- a/source/java/index.rst +++ /dev/null @@ -1,191 +0,0 @@ -========================= -Java Programming Examples -========================= - -Java programming section, which illustrates how to do various programing tasks -using Java programming language. - -Programs -======== - -Our intention is to present the programs from the 'Java Precisely' book here -with explanation. - -.. toctree:: - :maxdepth: 1 - - Comments - Layout - AutoBoxingUnboxing - ConversionPrimitive - VariableDeclaration - Scope - EqualityStrings - Concatenate - CountEs - Lexicographic - AlignNumbers - AbstractClass - AligningStrings - AllPathsTryCatchFinally - AnimatedCanvas - ArithmeticOperators - ArrayAssignmentTypeCheck - AssignmentNoCopyObjects - BinaryOutput - BinarySearchSortedArray - BitwiseOperators - BlockStatements - BuildingConcordance - CallingNonOverloaded - CallingOverloaded - CallingOverriddenConstructor - CallingOverriden - ClassesInterfaces - CompleteInputOutput - CompoundAssignment - ConcatCliArgs - ConcordanceUsingIterables - ConcreteCollection - ConditionalExpression - ConstraintsType - ConstructorOverloading - DeclaringCheckedException - DoWhileRollaDie - EmptyStatement - EnhancedForStatement - EqualsMethod - ExplicitIterable - ExplicitIterableWhileLoop - FieldAccess - FieldDeclarations - FieldInitializers - FloatingPointFactorial - FormattingDateAndTime - ForStatementIterable - GaussianPseudoRandom - GenericArrayLists - GenericClassLogging - GenericClassType - GenericInterfaceFunction - GenericLinkedList - GenericList - GenericMethodGenericClass - GenericQuickSort - GenericQuicksortComparable - GenericsLimitation - InefficientReplacement - InitializedArray - InnerObjects - InputOutputExamples - IntegerComparator - InternalPipes - IterationOverIterable - IteratorAnonymous - JavaFiveFeatures - LinkedHashSetRemoveDuplicates - LocaleSpecificDate - LocaleSpecificNumbers - LocalInnerClassInterator - LogicalOperators - MathematicalFunctions - MemberAccessModifiers - MemberClasses - MethodNameOverloading - MethodOverloadingHiding - MethodOverloadingParameterArray - MethodReturningIterable - MultiDimensionalArray - MultipleThreads - MutualExclusion - NestedForLoops - NonGenericArrayList - ObjectsAndClasses - ObjectsWithMultipleFields - ObtainedSubMap - OutputBuffering - PaddingString - Point - PrintHTMLTable - PrintingNumbers - PrivateMemberAccess - ProducerConsumer - RandomAccessReads - ReadingNumbers - ReadingNumbersLineByLine - ReadingPrintingDirHierarchy - ReflectionPublicMethods - ReflectiveAccessToField - ReflectiveCreation - ReflectiveInspection - ReflectiveObjectCreation - ReflectiveRetrieval - ReplaceOccurances - RepresentingWeekdays - SequenceIfElse - SerializationDistinctObject - SerializationSameObject - SetMembership - SetsKeysinHashMap - SeveralFieldsSameName - SingleIfElse - SocketCommunication - SpecifyingOutputEncoding - StoringResultsDatabase - StringArrayFile - StringComparator - StringFromCharArray - SubtypeRelations - SuperclassConstructor - SwitchOnEnum - SwitchStatement - SwitchStatementStrings - SynchronizedMethods - ThreeInterfaces - ThrowingExceptionFailure - TimeComparable - TopLevelClass - ToString - TreeSetRange - TryCatch - TryFinally - TypeErasure - TypeParameter - UncheckedCast - UnderstandingCollectionsbinarySearch - UnderstandingCollectionscopy - UniqueClassObject - UsingAppendableInterface - Usingassert - UsingassertsCheckAlgorithm - UsingBreakToExitLabeled - UsingBreakToTerminateLoop - UsingContinueStartIteration - UsingCustomAnnotation - UsingInterfacesAsTypes - UsingMultidimentionalArrays - UsingReturntoTerminateLoop - Usingthis - UsingthisObject - VesselHeirarchy - WeekdayNametoNumberHashMap - WhileLoop - WideningNarrowing - WildcardTypes - WorklistAlgorithm - - - -Interesting Programs -==================== - -.. toctree:: - :maxdepth: 1 - - Describe - HelloUnicode - HelloWorld - IfTest - ObjectCreation - OneDimensionalArray - ParameterPassing 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_binary_to_octal.rst b/source/python/algorithm_binary_to_octal.rst deleted file mode 100644 index e0ee8bf9..00000000 --- a/source/python/algorithm_binary_to_octal.rst +++ /dev/null @@ -1,33 +0,0 @@ -=============== -Binary to Octal -=============== - -Question --------- - -Convert the given binary number to octal. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_binary_to_octal.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_binary_to_octal.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_binary_to_octal.py` - * :python-better-explain:`algorithm_binary_to_octal.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_countingsort.rst b/source/python/algorithm_countingsort.rst deleted file mode 100644 index 2651aa20..00000000 --- a/source/python/algorithm_countingsort.rst +++ /dev/null @@ -1,32 +0,0 @@ -============= -Counting Sort -============= - -Question --------- - -This program illustrates the counting sort algorithm. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_countingsort.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_countingsort.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_countingsort.py` - * :python-better-explain:`algorithm_countingsort.rst` - diff --git a/source/python/algorithm_depth_first_search.rst b/source/python/algorithm_depth_first_search.rst deleted file mode 100644 index bb931174..00000000 --- a/source/python/algorithm_depth_first_search.rst +++ /dev/null @@ -1,32 +0,0 @@ -================== -Depth First Search -================== - -Question --------- - -This program illustrates the depth first search algorithm. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_depth_first_search.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_depth_first_search.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_depth_first_search.py` - * :python-better-explain:`algorithm_depth_first_search.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_euclid.rst b/source/python/algorithm_euclid.rst deleted file mode 100644 index 55bf5306..00000000 --- a/source/python/algorithm_euclid.rst +++ /dev/null @@ -1,32 +0,0 @@ -========================= -Euclid method to find GCD -========================= - -Question --------- - -Euclid's method to determine the greatest common divisor between two numbers. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_euclid.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_euclid.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_euclid.py` - * :python-better-explain:`algorithm_euclid.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_fact_with_memo.rst b/source/python/algorithm_fact_with_memo.rst deleted file mode 100644 index d863e8cc..00000000 --- a/source/python/algorithm_fact_with_memo.rst +++ /dev/null @@ -1,32 +0,0 @@ -======================== -Factorial with Memoizing -======================== - -Question --------- - -Illustrate finding the factorial of a given number, which memoizes the intermediate results. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_fact_with_memo.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_fact_with_memo.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_fact_with_memo.py` - * :python-better-explain:`algorithm_fact_with_memo.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_fibo2.rst b/source/python/algorithm_fibo2.rst deleted file mode 100644 index b4c30f0a..00000000 --- a/source/python/algorithm_fibo2.rst +++ /dev/null @@ -1,32 +0,0 @@ -============= -Fibonacci - 2 -============= - -Question --------- - -Implement the fibonacci series. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_fibo2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_fibo2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_fibo2.py` - * :python-better-explain:`algorithm_fibo2.rst` - diff --git a/source/python/algorithm_fri_13.rst b/source/python/algorithm_fri_13.rst deleted file mode 100644 index 70f0bd28..00000000 --- a/source/python/algorithm_fri_13.rst +++ /dev/null @@ -1,33 +0,0 @@ -=============== -Friday the 13th -=============== - -Question --------- - -Calculate the number of Friday the 13th from 1900 to 2009. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_fri_13.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_fri_13.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_fri_13.py` - * :python-better-explain:`algorithm_fri_13.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_hexlify.rst b/source/python/algorithm_hexlify.rst deleted file mode 100644 index 73edb1ba..00000000 --- a/source/python/algorithm_hexlify.rst +++ /dev/null @@ -1,31 +0,0 @@ -============================== -Encode a String to Hexadecimal -============================== - -Question --------- - -Write a program to encode a string to hexadecimal. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_hexlify.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_hexlify.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_hexlify.py` - * :python-better-explain:`algorithm_hexlify.rst` diff --git a/source/python/algorithm_hist.rst b/source/python/algorithm_hist.rst deleted file mode 100644 index 2c88e97c..00000000 --- a/source/python/algorithm_hist.rst +++ /dev/null @@ -1,33 +0,0 @@ -================== -Vertical Histogram -================== - -Question --------- - -Given a sentence, write a program that prints the vertical histogram of frequency of words in the sentence. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_hist.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_hist.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_hist.py` - * :python-better-explain:`algorithm_hist.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_lexical_analyzer_1.rst b/source/python/algorithm_lexical_analyzer_1.rst deleted file mode 100644 index bb8b4e67..00000000 --- a/source/python/algorithm_lexical_analyzer_1.rst +++ /dev/null @@ -1,49 +0,0 @@ -================ -Lexical Analyzer -================ - -Question --------- - -Write a Lexical Analyzer for the tokens. - -:: - - # Write the lexical analyzer for the tokens: - # Regular Expression Tokens Attribute-Value - # ws - - - # if if - - # then then - - # else else - - # id id pointer to table entry - # num num pointer to table entry - # < relop LT - # <= relop LE - # = relop EQ - # <> relop NE - # > relop GT - # >= relop GE - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_lexical_analyzer_1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_lexical_analyzer_1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_lexical_analyzer_1.py` - * :python-better-explain:`algorithm_lexical_analyzer_1.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_number_sets.rst b/source/python/algorithm_number_sets.rst deleted file mode 100644 index 63de74f2..00000000 --- a/source/python/algorithm_number_sets.rst +++ /dev/null @@ -1,32 +0,0 @@ -=========== -Number Sets -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_number_sets.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_number_sets.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_number_sets.py` - * :python-better-explain:`algorithm_number_sets.rst` - diff --git a/source/python/algorithm_prime_1.rst b/source/python/algorithm_prime_1.rst deleted file mode 100644 index 74381c55..00000000 --- a/source/python/algorithm_prime_1.rst +++ /dev/null @@ -1,32 +0,0 @@ -===================== -Prime Numbers Example -===================== - -Question --------- - -Generate first n prime numbers. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_prime_1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_prime_1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_prime_1.py` - * :python-better-explain:`algorithm_prime_1.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_quick_select.rst b/source/python/algorithm_quick_select.rst deleted file mode 100644 index b019a0ff..00000000 --- a/source/python/algorithm_quick_select.rst +++ /dev/null @@ -1,32 +0,0 @@ -============ -Quick Select -============ - -Question --------- - -Select the n greatest number using quick select algorithm. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_quick_select.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_quick_select.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_quick_select.py` - * :python-better-explain:`algorithm_quick_select.rst` - diff --git a/source/python/algorithm_quicksort.rst b/source/python/algorithm_quicksort.rst deleted file mode 100644 index 95041188..00000000 --- a/source/python/algorithm_quicksort.rst +++ /dev/null @@ -1,33 +0,0 @@ -========= -Quicksort -========= - -Question --------- - -Implement Quicksort algorithm; Implement the pivot element section. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_quicksort.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_quicksort.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_quicksort.py` - * :python-better-explain:`algorithm_quicksort.rst` - diff --git a/source/python/algorithm_scrmable.rst b/source/python/algorithm_scrmable.rst deleted file mode 100644 index 638fea76..00000000 --- a/source/python/algorithm_scrmable.rst +++ /dev/null @@ -1,32 +0,0 @@ -======== -Scrmable -======== - -Question --------- - -Scramble the words in the sentence. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_scrmable.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_scrmable.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_scrmable.py` - * :python-better-explain:`algorithm_scrmable.rst` - diff --git a/source/python/algorithm_sorting_ex1.rst b/source/python/algorithm_sorting_ex1.rst deleted file mode 100644 index 15e87add..00000000 --- a/source/python/algorithm_sorting_ex1.rst +++ /dev/null @@ -1,32 +0,0 @@ -=========== -Sorting Ex1 -=========== - -Question --------- - -Demonstrate sorting and the use of key parameter. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_sorting_ex1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_sorting_ex1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_sorting_ex1.py` - * :python-better-explain:`algorithm_sorting_ex1.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_subtract_hexadecimals.rst b/source/python/algorithm_subtract_hexadecimals.rst deleted file mode 100644 index 65adc38c..00000000 --- a/source/python/algorithm_subtract_hexadecimals.rst +++ /dev/null @@ -1,32 +0,0 @@ -===================== -Subtract Hexadecimals -===================== - -Question --------- - -Routine to subtract two hexadecimal numbers. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_subtract_hexadecimals.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_subtract_hexadecimals.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_subtract_hexadecimals.py` - * :python-better-explain:`algorithm_subtract_hexadecimals.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_tree.rst b/source/python/algorithm_tree.rst deleted file mode 100644 index e84a5726..00000000 --- a/source/python/algorithm_tree.rst +++ /dev/null @@ -1,32 +0,0 @@ -==== -Tree -==== - -Question --------- - -Demonstrate creation of a node in the Tree. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_tree.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_tree.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_tree.py` - * :python-better-explain:`algorithm_tree.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_class_same_object.rst b/source/python/design_class_same_object.rst deleted file mode 100644 index 05cada7b..00000000 --- a/source/python/design_class_same_object.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Class Same object -================= - -Question --------- - -Method calls on an object. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_class_same_object.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_class_same_object.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_class_same_object.py` - * :python-better-explain:`design_class_same_object.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_dict_list.rst b/source/python/design_dict_list.rst deleted file mode 100644 index 8a992344..00000000 --- a/source/python/design_dict_list.rst +++ /dev/null @@ -1,34 +0,0 @@ -========= -Dict List -========= - -Question --------- - -Function arguments. Positional, List and Keyword Arguments. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_dict_list.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_dict_list.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_dict_list.py` - * :python-better-explain:`design_dict_list.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_gen1.rst b/source/python/design_gen1.rst deleted file mode 100644 index 70b1d622..00000000 --- a/source/python/design_gen1.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Generator Example 1 -=================== - -Question --------- - -Example of a generator. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_gen1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_gen1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_gen1.py` - * :python-better-explain:`design_gen1.rst` - diff --git a/source/python/design_gen2.rst b/source/python/design_gen2.rst deleted file mode 100644 index 57d21570..00000000 --- a/source/python/design_gen2.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Generator Example -================= - -Question --------- - -Generator Example with a conditional. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_gen2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_gen2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_gen2.py` - * :python-better-explain:`design_gen2.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_generator_countdown.rst b/source/python/design_generator_countdown.rst deleted file mode 100644 index 789bab25..00000000 --- a/source/python/design_generator_countdown.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Generator countdown -=================== - -Question --------- - -Generator demonstrating countdown from a particular value. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_generator_countdown.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_generator_countdown.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_generator_countdown.py` - * :python-better-explain:`design_generator_countdown.rst` - diff --git a/source/python/design_generator_countdown2.rst b/source/python/design_generator_countdown2.rst deleted file mode 100644 index 322e7e6b..00000000 --- a/source/python/design_generator_countdown2.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Generator countdown2 -==================== - -Question --------- - -Countdown from n generator. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_generator_countdown2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_generator_countdown2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_generator_countdown2.py` - * :python-better-explain:`design_generator_countdown2.rst` - diff --git a/source/python/design_generator_example1.rst b/source/python/design_generator_example1.rst deleted file mode 100644 index 705e895a..00000000 --- a/source/python/design_generator_example1.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================================= -Generator Example - Infinite Fibonacci Series -============================================= - -Question --------- - -Infinite fibonacci series using generators. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_generator_example1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_generator_example1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_generator_example1.py` - * :python-better-explain:`design_generator_example1.rst` - diff --git a/source/python/design_generator_execution.rst b/source/python/design_generator_execution.rst deleted file mode 100644 index 59687baa..00000000 --- a/source/python/design_generator_execution.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Generator Execution -=================== - -Question --------- - -Explaining Generators and their type. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_generator_execution.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_generator_execution.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_generator_execution.py` - * :python-better-explain:`design_generator_execution.rst` - diff --git a/source/python/design_generator_follow.rst b/source/python/design_generator_follow.rst deleted file mode 100644 index 90d46781..00000000 --- a/source/python/design_generator_follow.rst +++ /dev/null @@ -1,35 +0,0 @@ -======================================= -Generator - Writing a tail like utility -======================================= - -Question --------- - -Writing a `tail` like utility to read a file using generator. - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_generator_follow.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_generator_follow.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_generator_follow.py` - * :python-better-explain:`design_generator_follow.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_ex1.rst b/source/python/design_iterator_ex1.rst deleted file mode 100644 index ff7b50db..00000000 --- a/source/python/design_iterator_ex1.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================================== -Iterator Example - Fibonacci Sequence -===================================== - -Question --------- - -Example of an iterator generating Fibonacci sequence - -Solution --------- - -.. literalinclude:: ../../languages/python/design_iterator_ex1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_iterator_ex1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_iterator_ex1.py` - * :python-better-explain:`design_iterator_ex1.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_oop1.rst b/source/python/design_oop1.rst deleted file mode 100644 index 4affb9a6..00000000 --- a/source/python/design_oop1.rst +++ /dev/null @@ -1,34 +0,0 @@ -==== -oop1 -==== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/design_oop1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_oop1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_oop1.py` - * :python-better-explain:`design_oop1.rst` - diff --git a/source/python/design_optimization2.rst b/source/python/design_optimization2.rst deleted file mode 100644 index 07c5f947..00000000 --- a/source/python/design_optimization2.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Dis-assemble -============ - -Question --------- - -Dis-assemble a nested sequence - -Solution --------- - -.. literalinclude:: ../../languages/python/design_optimization2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_optimization2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_optimization2.py` - * :python-better-explain:`design_optimization2.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_sorted_loop2.rst b/source/python/design_sorted_loop2.rst deleted file mode 100644 index 05e2d35f..00000000 --- a/source/python/design_sorted_loop2.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Sorted Loop2 -============ - -Question --------- - -Sorted Loop comparision with the previous program. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_sorted_loop2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_sorted_loop2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_sorted_loop2.py` - * :python-better-explain:`design_sorted_loop2.rst` - diff --git a/source/python/design_space_efficient_dict.rst b/source/python/design_space_efficient_dict.rst deleted file mode 100644 index 9e007ffb..00000000 --- a/source/python/design_space_efficient_dict.rst +++ /dev/null @@ -1,35 +0,0 @@ -==================== -Space Efficient Dict -==================== - -Question --------- - -Designing a space efficient dictionary. - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_space_efficient_dict.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_space_efficient_dict.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_space_efficient_dict.py` - * :python-better-explain:`design_space_efficient_dict.rst` - diff --git a/source/python/design_stack.rst b/source/python/design_stack.rst deleted file mode 100644 index a28dffc9..00000000 --- a/source/python/design_stack.rst +++ /dev/null @@ -1,34 +0,0 @@ -===== -Stack -===== - -Question --------- - -Stack operations in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_stack.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_stack.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_stack.py` - * :python-better-explain:`design_stack.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/design_try_except.rst b/source/python/design_try_except.rst deleted file mode 100644 index f14a31cb..00000000 --- a/source/python/design_try_except.rst +++ /dev/null @@ -1,34 +0,0 @@ -========== -Try Except -========== - -Question --------- - -Demonstrate try except statement in python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_try_except.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_try_except.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_try_except.py` - * :python-better-explain:`design_try_except.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_import_zip_with_py.rst b/source/python/files_import_zip_with_py.rst deleted file mode 100644 index 03ba415a..00000000 --- a/source/python/files_import_zip_with_py.rst +++ /dev/null @@ -1,43 +0,0 @@ -============================= -Import a zipfile with py file -============================= - -Question --------- - -This snippet creates a zip file with a '.py' inside it. Demonstrates python -ability to import a zipfile and run the function inside it. - -Solution --------- - -.. literalinclude:: ../../languages/python/files_import_zip_with_py.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/files_import_zip_with_py.py - :language: python - :codesite: ideone - -Explanation -=========== - -Running this will emit an output. - -:: - - hello world from /var/folders/_2/kqmfvpxj3_l3dnj5wq1y6j1c0000gn/T/tmpK1ePKl.zip/hello.py - - -Note that I have imported `import hello` using a module name as the name of -the zipfile and accessed a function inside it. This demonstrates only ability -to package python files and run it as a package. - - - - -.. seealso:: - - * :python-suggest-improve:`files_import_zip_with_py.py` - * :python-better-explain:`files_import_zip_with_py.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 11c2ebea..00000000 --- a/source/python/index.rst +++ /dev/null @@ -1,257 +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_binary_to_octal - algorithm_cellauto - algorithm_checking_string_text_or_binary - algorithm_countingsort - algorithm_depth_first_search - algorithm_eratosthenes - algorithm_euclid - algorithm_fact_with_memo - algorithm_fact2 - algorithm_fibo - algorithm_fibo2 - algorithm_fri_13 - algorithm_graph - algorithm_hanoi - algorithm_hexlify - algorithm_hist - algorithm_insertion - algorithm_int_to_roman - algorithm_lexical_analyzer_1 - algorithm_locate - algorithm_maxsort - algorithm_mergesort - algorithm_npuzzle - algorithm_number_sets - algorithm_prime_1 - algorithm_pyex_multiprocessing - algorithm_pyex2_multiprocessing - algorithm_quick_select - algorithm_quicksort - algorithm_scrmable - algorithm_sorting_ex1 - algorithm_spelling - algorithm_splitter - algorithm_subtract_hexadecimals - algorithm_syllablecount - algorithm_toss_coins - algorithm_traversal - algorithm_tree - algorithm_tree2 - -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_class_same_object - design_closure_example1 - design_closure1 - design_context_2 - design_contextmanager - design_contextmanager_ex - design_decorator3 - design_dict_list - design_ex_iterable27 - design_func_args - design_gen1 - design_gen2 - design_generator - design_generator_countdown - design_generator_countdown2 - design_generator_example1 - design_generator_execution - design_generator_follow - design_getattribute_example1 - design_getattribute_example2 - design_hextobin - design_inheritance - design_iterator_ex1 - design_iterator_ex2 - design_object_size - design_oop1 - design_optimization2 - design_python_objects_type - design_python3_meta_ex1 - design_restricter_class - design_simple_closure - design_slice_ellipses - design_sorted_loop - design_sorted_loop2 - design_space_efficient_dict - design_stack - design_stackinspection - design_struct_example - design_total_ordering - design_traceit - design_try_except - - -Networking -========== - -This program demonstrates networking and socket calls. Anything to do with -servers and clients. - - -.. toctree:: - :maxdepth: 1 - - networking_allifaces - networking_allipaddress - networking_bug_gethostbyname - networking_email1 - networking_email2 - networking_email3 - networking_fetchrfc - networking_googlesearch - networking_socket_client - networking_socket_example1 - networking_socket_example2 - networking_socket_example3 - networking_socket_example4 - networking_twisted_parallel1 - networking_twisted_parallel2 - networking_twisted1 - networking_twisted2 - networking_twisted3 - networking_twisted4 - networking_twisted5 - networking_udp_time - networking_udp1 - networking_udp2 - -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 - -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 - - -Web -=== - -These deal with websites, webapplications and work on top of networking layer. - -.. toctree:: - :maxdepth: 1 - - web_cgi_ex - web_codepad_post - web_crawl - web_crawl2 - web_http_auth_header_code - web_httplib_example_1 - web_httplib_example_2 - web_httplib_example_3 - web_httplib_head - web_scan_web - web_server - web_simple_http_processor - web_urllib1 - web_urllib2_1 - web_urllib2_add_data - web_urllib2_auth_ex1 - web_urllib2_basic_digest1 - web_urllib2_basic1 - web_urllib2_basic2 - web_urllib2_basic3 - web_urllib2_binary_upload - web_urllib2_debug_headers - web_urllib2_digest - web_urllib2_digest2 - web_urllib2_headers_ex1 - web_urllib2_proxy_auth - web_urllib2_test - web_urllib2_1 - files_read_specific_line - files_count_lines_large_file - files_processing_every_word - files_random_access_input_output - files_reading_zipfile - - files_import_zip_with_py - diff --git a/source/python/networking_allifaces.rst b/source/python/networking_allifaces.rst deleted file mode 100644 index e1120521..00000000 --- a/source/python/networking_allifaces.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================= -All Networking Interfaces -========================= - -Question --------- - -List Network Interfaces - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_allifaces.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_allifaces.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_allifaces.py` - * :python-better-explain:`networking_allifaces.rst` - diff --git a/source/python/networking_allipaddress.rst b/source/python/networking_allipaddress.rst deleted file mode 100644 index 9f070334..00000000 --- a/source/python/networking_allipaddress.rst +++ /dev/null @@ -1,35 +0,0 @@ -============================ -All Ipaddress of your system -============================ - -Question --------- - -The program gets all the ipaddress assigned to all the interfaces -in your machine. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_allipaddress.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_allipaddress.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_allipaddress.py` - * :python-better-explain:`networking_allipaddress.rst` - diff --git a/source/python/networking_bug_gethostbyname.rst b/source/python/networking_bug_gethostbyname.rst deleted file mode 100644 index 2e14eb77..00000000 --- a/source/python/networking_bug_gethostbyname.rst +++ /dev/null @@ -1,36 +0,0 @@ -============= -Gethostbyname -============= - -Question --------- - -Generate a random domain name and see if it actually exists by doing a -gethostbyname call. - - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_bug_gethostbyname.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_bug_gethostbyname.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_bug_gethostbyname.py` - * :python-better-explain:`networking_bug_gethostbyname.rst` - diff --git a/source/python/networking_email1.rst b/source/python/networking_email1.rst deleted file mode 100644 index eb76130f..00000000 --- a/source/python/networking_email1.rst +++ /dev/null @@ -1,34 +0,0 @@ -======= -Email 1 -======= - -Question --------- - -Demonstrate sending of an email. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_email1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_email1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_email1.py` - * :python-better-explain:`networking_email1.rst` - diff --git a/source/python/networking_email2.rst b/source/python/networking_email2.rst deleted file mode 100644 index ee540e82..00000000 --- a/source/python/networking_email2.rst +++ /dev/null @@ -1,34 +0,0 @@ -======= -Email 2 -======= - -Question --------- - -Email sending program 2 - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_email2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_email2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_email2.py` - * :python-better-explain:`networking_email2.rst` - diff --git a/source/python/networking_email3.rst b/source/python/networking_email3.rst deleted file mode 100644 index 12ad18bb..00000000 --- a/source/python/networking_email3.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Email - Multipart Mime -====================== - -Question --------- - -Send an email with Multipart Mime content. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_email3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_email3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_email3.py` - * :python-better-explain:`networking_email3.rst` - diff --git a/source/python/networking_fetchrfc.rst b/source/python/networking_fetchrfc.rst deleted file mode 100644 index ae69e268..00000000 --- a/source/python/networking_fetchrfc.rst +++ /dev/null @@ -1,34 +0,0 @@ -========= -Fetch RFC -========= - -Question --------- - -Fetch an Internet RFC - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_fetchrfc.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_fetchrfc.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_fetchrfc.py` - * :python-better-explain:`networking_fetchrfc.rst` - diff --git a/source/python/networking_googlesearch.rst b/source/python/networking_googlesearch.rst deleted file mode 100644 index acf79b7a..00000000 --- a/source/python/networking_googlesearch.rst +++ /dev/null @@ -1,34 +0,0 @@ -============= -Google Search -============= - -Question --------- - -Google Search using AJAX APIs - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_googlesearch.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_googlesearch.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_googlesearch.py` - * :python-better-explain:`networking_googlesearch.rst` - diff --git a/source/python/networking_socket_client.rst b/source/python/networking_socket_client.rst deleted file mode 100644 index ba583d69..00000000 --- a/source/python/networking_socket_client.rst +++ /dev/null @@ -1,34 +0,0 @@ -============= -Socket Client -============= - -Question --------- - -Example creation of socket client. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_socket_client.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_socket_client.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_socket_client.py` - * :python-better-explain:`networking_socket_client.rst` - diff --git a/source/python/networking_socket_example1.rst b/source/python/networking_socket_example1.rst deleted file mode 100644 index 7d74977a..00000000 --- a/source/python/networking_socket_example1.rst +++ /dev/null @@ -1,35 +0,0 @@ -=============== -Socket Example1 -=============== - -Question --------- - -Socket example 1 for getservbyname - - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_socket_example1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_socket_example1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_socket_example1.py` - * :python-better-explain:`networking_socket_example1.rst` - diff --git a/source/python/networking_socket_example2.rst b/source/python/networking_socket_example2.rst deleted file mode 100644 index b00f542a..00000000 --- a/source/python/networking_socket_example2.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Socket Example2 -=============== - -Question --------- - -Create a dictionary mapping socket module constants to their names. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_socket_example2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_socket_example2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_socket_example2.py` - * :python-better-explain:`networking_socket_example2.rst` - diff --git a/source/python/networking_socket_example3.rst b/source/python/networking_socket_example3.rst deleted file mode 100644 index 653dc4ff..00000000 --- a/source/python/networking_socket_example3.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Socket Example3 -=============== - -Question --------- - -Different types of socket constants. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_socket_example3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_socket_example3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_socket_example3.py` - * :python-better-explain:`networking_socket_example3.rst` - diff --git a/source/python/networking_socket_example4.rst b/source/python/networking_socket_example4.rst deleted file mode 100644 index ef98c606..00000000 --- a/source/python/networking_socket_example4.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Socket Example4 -=============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_socket_example4.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_socket_example4.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_socket_example4.py` - * :python-better-explain:`networking_socket_example4.rst` - diff --git a/source/python/networking_twisted1.rst b/source/python/networking_twisted1.rst deleted file mode 100644 index 31bbdff1..00000000 --- a/source/python/networking_twisted1.rst +++ /dev/null @@ -1,35 +0,0 @@ -======== -Twisted1 -======== - -Question --------- - -Parallel Download using Twisted. - - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_twisted1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_twisted1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_twisted1.py` - * :python-better-explain:`networking_twisted1.rst` - diff --git a/source/python/networking_twisted2.rst b/source/python/networking_twisted2.rst deleted file mode 100644 index f3bf777e..00000000 --- a/source/python/networking_twisted2.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Twisted2 -======== - -Question --------- - -Use of getProcessOutput in twisted. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_twisted2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_twisted2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_twisted2.py` - * :python-better-explain:`networking_twisted2.rst` - diff --git a/source/python/networking_twisted3.rst b/source/python/networking_twisted3.rst deleted file mode 100644 index 961cfa09..00000000 --- a/source/python/networking_twisted3.rst +++ /dev/null @@ -1,35 +0,0 @@ -======== -Twisted3 -======== - -Question --------- - -Parse the html of a file in twisted. - - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_twisted3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_twisted3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_twisted3.py` - * :python-better-explain:`networking_twisted3.rst` - diff --git a/source/python/networking_twisted4.rst b/source/python/networking_twisted4.rst deleted file mode 100644 index fb5e70b0..00000000 --- a/source/python/networking_twisted4.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Twisted4 -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_twisted4.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_twisted4.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_twisted4.py` - * :python-better-explain:`networking_twisted4.rst` - diff --git a/source/python/networking_twisted5.rst b/source/python/networking_twisted5.rst deleted file mode 100644 index cd01f9ec..00000000 --- a/source/python/networking_twisted5.rst +++ /dev/null @@ -1,35 +0,0 @@ -======== -Twisted5 -======== - -Question --------- - -A twisted program outline. - - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_twisted5.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_twisted5.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_twisted5.py` - * :python-better-explain:`networking_twisted5.rst` - diff --git a/source/python/networking_twisted_parallel1.rst b/source/python/networking_twisted_parallel1.rst deleted file mode 100644 index 3732062f..00000000 --- a/source/python/networking_twisted_parallel1.rst +++ /dev/null @@ -1,35 +0,0 @@ -================= -Twisted Parallel1 -================= - -Question --------- - -Parallel Download using Twisted. - - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_twisted_parallel1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_twisted_parallel1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_twisted_parallel1.py` - * :python-better-explain:`networking_twisted_parallel1.rst` - diff --git a/source/python/networking_twisted_parallel2.rst b/source/python/networking_twisted_parallel2.rst deleted file mode 100644 index d308f64c..00000000 --- a/source/python/networking_twisted_parallel2.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Twisted Parallel2 -================= - -Question --------- - -Parallel Execution of a Task - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_twisted_parallel2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_twisted_parallel2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_twisted_parallel2.py` - * :python-better-explain:`networking_twisted_parallel2.rst` - diff --git a/source/python/networking_udp1.rst b/source/python/networking_udp1.rst deleted file mode 100644 index c6f32318..00000000 --- a/source/python/networking_udp1.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Udp Connection -1 -================= - -Question --------- - -Example of establishing a UDP connection. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_udp1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_udp1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_udp1.py` - * :python-better-explain:`networking_udp1.rst` - diff --git a/source/python/networking_udp2.rst b/source/python/networking_udp2.rst deleted file mode 100644 index e67f6373..00000000 --- a/source/python/networking_udp2.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Udp Example - 2 -=============== - -Question --------- - -Example of establishing a UDP Connection 2. - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_udp2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_udp2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_udp2.py` - * :python-better-explain:`networking_udp2.rst` - diff --git a/source/python/networking_udp_time.rst b/source/python/networking_udp_time.rst deleted file mode 100644 index 085ede97..00000000 --- a/source/python/networking_udp_time.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Udp Time -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/networking_udp_time.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/networking_udp_time.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`networking_udp_time.py` - * :python-better-explain:`networking_udp_time.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/web_cgi_ex.rst b/source/python/web_cgi_ex.rst deleted file mode 100644 index 4b241b6e..00000000 --- a/source/python/web_cgi_ex.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Cgi Example -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_cgi_ex.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_cgi_ex.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_cgi_ex.py` - * :python-better-explain:`web_cgi_ex.rst` - diff --git a/source/python/web_codepad_post.rst b/source/python/web_codepad_post.rst deleted file mode 100644 index 965809f8..00000000 --- a/source/python/web_codepad_post.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Codepad Post -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_codepad_post.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_codepad_post.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_codepad_post.py` - * :python-better-explain:`web_codepad_post.rst` - diff --git a/source/python/web_crawl.rst b/source/python/web_crawl.rst deleted file mode 100644 index b778b3e0..00000000 --- a/source/python/web_crawl.rst +++ /dev/null @@ -1,34 +0,0 @@ -===== -Crawl -===== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_crawl.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_crawl.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_crawl.py` - * :python-better-explain:`web_crawl.rst` - diff --git a/source/python/web_crawl2.rst b/source/python/web_crawl2.rst deleted file mode 100644 index 722fa10c..00000000 --- a/source/python/web_crawl2.rst +++ /dev/null @@ -1,34 +0,0 @@ -====== -Crawl2 -====== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_crawl2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_crawl2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_crawl2.py` - * :python-better-explain:`web_crawl2.rst` - diff --git a/source/python/web_http_auth_header_code.rst b/source/python/web_http_auth_header_code.rst deleted file mode 100644 index a9072ecc..00000000 --- a/source/python/web_http_auth_header_code.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -http Auth Header Code -===================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_http_auth_header_code.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_http_auth_header_code.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_http_auth_header_code.py` - * :python-better-explain:`web_http_auth_header_code.rst` - diff --git a/source/python/web_httplib_example_1.rst b/source/python/web_httplib_example_1.rst deleted file mode 100644 index 7fed3b73..00000000 --- a/source/python/web_httplib_example_1.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Httplib Example1 -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_httplib_example_1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_httplib_example_1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_httplib_example_1.py` - * :python-better-explain:`web_httplib_example_1.rst` - diff --git a/source/python/web_httplib_example_2.rst b/source/python/web_httplib_example_2.rst deleted file mode 100644 index c6645197..00000000 --- a/source/python/web_httplib_example_2.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Httplib Example2 -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_httplib_example_2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_httplib_example_2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_httplib_example_2.py` - * :python-better-explain:`web_httplib_example_2.rst` - diff --git a/source/python/web_httplib_example_3.rst b/source/python/web_httplib_example_3.rst deleted file mode 100644 index db90cfb6..00000000 --- a/source/python/web_httplib_example_3.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Httplib Example3 -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_httplib_example_3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_httplib_example_3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_httplib_example_3.py` - * :python-better-explain:`web_httplib_example_3.rst` - diff --git a/source/python/web_httplib_head.rst b/source/python/web_httplib_head.rst deleted file mode 100644 index c27792b9..00000000 --- a/source/python/web_httplib_head.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Httplib Head -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_httplib_head.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_httplib_head.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_httplib_head.py` - * :python-better-explain:`web_httplib_head.rst` - diff --git a/source/python/web_scan_web.rst b/source/python/web_scan_web.rst deleted file mode 100644 index 4bdf8c2a..00000000 --- a/source/python/web_scan_web.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Scan Web -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_scan_web.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_scan_web.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_scan_web.py` - * :python-better-explain:`web_scan_web.rst` - diff --git a/source/python/web_server.rst b/source/python/web_server.rst deleted file mode 100644 index 9085f0c0..00000000 --- a/source/python/web_server.rst +++ /dev/null @@ -1,34 +0,0 @@ -====== -Server -====== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_server.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_server.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_server.py` - * :python-better-explain:`web_server.rst` - diff --git a/source/python/web_simple_http_processor.rst b/source/python/web_simple_http_processor.rst deleted file mode 100644 index afb0da4c..00000000 --- a/source/python/web_simple_http_processor.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Simple Http Processor -===================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_simple_http_processor.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_simple_http_processor.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_simple_http_processor.py` - * :python-better-explain:`web_simple_http_processor.rst` - diff --git a/source/python/web_urllib1.rst b/source/python/web_urllib1.rst deleted file mode 100644 index 56c625f2..00000000 --- a/source/python/web_urllib1.rst +++ /dev/null @@ -1,34 +0,0 @@ -======= -Urllib1 -======= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib1.py` - * :python-better-explain:`web_urllib1.rst` - diff --git a/source/python/web_urllib2_1.rst b/source/python/web_urllib2_1.rst deleted file mode 100644 index 8bb0821f..00000000 --- a/source/python/web_urllib2_1.rst +++ /dev/null @@ -1,34 +0,0 @@ -========= -Urllib2-1 -========= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_1.py` - * :python-better-explain:`web_urllib2_1.rst` - diff --git a/source/python/web_urllib2_add_data.rst b/source/python/web_urllib2_add_data.rst deleted file mode 100644 index fec49185..00000000 --- a/source/python/web_urllib2_add_data.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Urllib2 Add Data -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_add_data.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_add_data.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_add_data.py` - * :python-better-explain:`web_urllib2_add_data.rst` - diff --git a/source/python/web_urllib2_auth_ex1.rst b/source/python/web_urllib2_auth_ex1.rst deleted file mode 100644 index 54a87b0d..00000000 --- a/source/python/web_urllib2_auth_ex1.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Urllib2 Auth Example1 -===================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_auth_ex1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_auth_ex1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_auth_ex1.py` - * :python-better-explain:`web_urllib2_auth_ex1.rst` - diff --git a/source/python/web_urllib2_basic1.rst b/source/python/web_urllib2_basic1.rst deleted file mode 100644 index 750f4c82..00000000 --- a/source/python/web_urllib2_basic1.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Urllib2 Basic1 -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_basic1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_basic1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_basic1.py` - * :python-better-explain:`web_urllib2_basic1.rst` - diff --git a/source/python/web_urllib2_basic2.rst b/source/python/web_urllib2_basic2.rst deleted file mode 100644 index 9c326b40..00000000 --- a/source/python/web_urllib2_basic2.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Urllib2 Basic2 -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_basic2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_basic2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_basic2.py` - * :python-better-explain:`web_urllib2_basic2.rst` - diff --git a/source/python/web_urllib2_basic3.rst b/source/python/web_urllib2_basic3.rst deleted file mode 100644 index 2783b316..00000000 --- a/source/python/web_urllib2_basic3.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Urllib2 Basic3 -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_basic3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_basic3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_basic3.py` - * :python-better-explain:`web_urllib2_basic3.rst` - diff --git a/source/python/web_urllib2_basic_digest1.rst b/source/python/web_urllib2_basic_digest1.rst deleted file mode 100644 index 5570e098..00000000 --- a/source/python/web_urllib2_basic_digest1.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Urllib2 Basic Digest1 -===================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_basic_digest1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_basic_digest1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_basic_digest1.py` - * :python-better-explain:`web_urllib2_basic_digest1.rst` - diff --git a/source/python/web_urllib2_binary_upload.rst b/source/python/web_urllib2_binary_upload.rst deleted file mode 100644 index a1566320..00000000 --- a/source/python/web_urllib2_binary_upload.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Urllib2 Binary Upload -===================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_binary_upload.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_binary_upload.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_binary_upload.py` - * :python-better-explain:`web_urllib2_binary_upload.rst` - diff --git a/source/python/web_urllib2_debug_headers.rst b/source/python/web_urllib2_debug_headers.rst deleted file mode 100644 index 903a1c6f..00000000 --- a/source/python/web_urllib2_debug_headers.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Urllib2 Debug Headers -===================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_debug_headers.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_debug_headers.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_debug_headers.py` - * :python-better-explain:`web_urllib2_debug_headers.rst` - diff --git a/source/python/web_urllib2_digest.rst b/source/python/web_urllib2_digest.rst deleted file mode 100644 index 366410d6..00000000 --- a/source/python/web_urllib2_digest.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Urllib2 Digest -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_digest.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_digest.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_digest.py` - * :python-better-explain:`web_urllib2_digest.rst` - diff --git a/source/python/web_urllib2_digest2.rst b/source/python/web_urllib2_digest2.rst deleted file mode 100644 index 530b2d6c..00000000 --- a/source/python/web_urllib2_digest2.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Urllib2 Digest2 -=============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_digest2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_digest2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_digest2.py` - * :python-better-explain:`web_urllib2_digest2.rst` - diff --git a/source/python/web_urllib2_headers_ex1.rst b/source/python/web_urllib2_headers_ex1.rst deleted file mode 100644 index 20e6ce53..00000000 --- a/source/python/web_urllib2_headers_ex1.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================== -Urllib2 Headers Example1 -======================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_headers_ex1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_headers_ex1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_headers_ex1.py` - * :python-better-explain:`web_urllib2_headers_ex1.rst` - diff --git a/source/python/web_urllib2_proxy_auth.rst b/source/python/web_urllib2_proxy_auth.rst deleted file mode 100644 index c3d3799f..00000000 --- a/source/python/web_urllib2_proxy_auth.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Urllib2 Proxy Auth -================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_proxy_auth.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_proxy_auth.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_proxy_auth.py` - * :python-better-explain:`web_urllib2_proxy_auth.rst` - diff --git a/source/python/web_urllib2_test.rst b/source/python/web_urllib2_test.rst deleted file mode 100644 index 2f015528..00000000 --- a/source/python/web_urllib2_test.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Urllib2 Test -============ - -Question --------- - -An example of using python urllib2 using `HTTPDigestAuthHandler` - -Solution --------- - -.. literalinclude:: ../../languages/python/web_urllib2_test.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/web_urllib2_test.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`web_urllib2_test.py` - * :python-better-explain:`web_urllib2_test.rst` - diff --git a/source/requirements.txt b/source/requirements.txt index 59aa86cc..0a8cfb19 100644 --- a/source/requirements.txt +++ b/source/requirements.txt @@ -1 +1,3 @@ +pydata-sphinx-theme sphinx_bootstrap_theme +piccolo-theme diff --git a/source/ruby/being_rescue_else_ensure.rst b/source/ruby/being_rescue_else_ensure.rst deleted file mode 100644 index 26304aaa..00000000 --- a/source/ruby/being_rescue_else_ensure.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================== -Being Rescue Else Ensure -======================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/being_rescue_else_ensure.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/being_rescue_else_ensure.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`being_rescue_else_ensure.rb` - * :ruby-better-explain:`being_rescue_else_ensure.rst` - diff --git a/source/ruby/check_nil.rst b/source/ruby/check_nil.rst deleted file mode 100644 index c6a461a4..00000000 --- a/source/ruby/check_nil.rst +++ /dev/null @@ -1,34 +0,0 @@ -========= -Check Nil -========= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/check_nil.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/check_nil.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`check_nil.rb` - * :ruby-better-explain:`check_nil.rst` - diff --git a/source/ruby/class_and_object.rst b/source/ruby/class_and_object.rst deleted file mode 100644 index 05d1f2ae..00000000 --- a/source/ruby/class_and_object.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Class And Object -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/class_and_object.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/class_and_object.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`class_and_object.rb` - * :ruby-better-explain:`class_and_object.rst` - diff --git a/source/ruby/conditionals.rst b/source/ruby/conditionals.rst deleted file mode 100644 index 6d8defd7..00000000 --- a/source/ruby/conditionals.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Conditionals -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/conditionals.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/conditionals.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`conditionals.rb` - * :ruby-better-explain:`conditionals.rst` - diff --git a/source/ruby/constant_assignment.rst b/source/ruby/constant_assignment.rst deleted file mode 100644 index 87069daa..00000000 --- a/source/ruby/constant_assignment.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================== -Constant Assignment -=================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/constant_assignment.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/constant_assignment.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`constant_assignment.rb` - * :ruby-better-explain:`constant_assignment.rst` - diff --git a/source/ruby/forloop.rst b/source/ruby/forloop.rst deleted file mode 100644 index 4e2d04f0..00000000 --- a/source/ruby/forloop.rst +++ /dev/null @@ -1,32 +0,0 @@ -========= -For loops -========= - -Demonstrate the for loop in Ruby. - -Solution --------- - -.. literalinclude:: ../../languages/ruby/forloop.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/forloop.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - -Iterating using the construct `for x in container` will iterate through the -values of the array. - - - - - -.. seealso:: - - * :ruby-suggest-improve:`forloop.rb` - * :ruby-better-explain:`forloop.rst` - diff --git a/source/ruby/handle_exceptions.rst b/source/ruby/handle_exceptions.rst deleted file mode 100644 index 3b310ca1..00000000 --- a/source/ruby/handle_exceptions.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Handle Exceptions -================= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/handle_exceptions.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/handle_exceptions.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`handle_exceptions.rb` - * :ruby-better-explain:`handle_exceptions.rst` - diff --git a/source/ruby/if_statement.rst b/source/ruby/if_statement.rst deleted file mode 100644 index e71c0a11..00000000 --- a/source/ruby/if_statement.rst +++ /dev/null @@ -1,35 +0,0 @@ -============ -If Statement -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/if_statement.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/if_statement.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`if_statement.rb` - * :ruby-better-explain:`if_statement.rst` - - diff --git a/source/ruby/include_modules.rst b/source/ruby/include_modules.rst deleted file mode 100644 index f61a6f12..00000000 --- a/source/ruby/include_modules.rst +++ /dev/null @@ -1,35 +0,0 @@ -=============== -Include Modules -=============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/include_modules.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/include_modules.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`include_modules.rb` - * :ruby-better-explain:`include_modules.rst` - - diff --git a/source/ruby/index.rst b/source/ruby/index.rst deleted file mode 100644 index f14a7461..00000000 --- a/source/ruby/index.rst +++ /dev/null @@ -1,43 +0,0 @@ -========================= -Ruby Programming Examples -========================= - -Ruby programming section, illustrates how to do various programing tasks using -Ruby programming language. - -Common Programming Tasks -======================== -This is an implementation of a well known CS algorithm. - -.. toctree:: - :maxdepth: 1 - - being_rescue_else_ensure - check_nil - class_and_object - conditionals - constant_assignment - forloop - handle_exceptions - if_statement - include_modules - introspect - iterate_each - kernel_method - module_mixin - modules_with_methods - open_url - puts_examples - puts_functionname - require_stmt - ruby_function - ruby5 - ruby7 - ruby13 - ruby16 - see_backtrace - simpleNumber - string_methods - string_templates - string_times - tc_simpleNumber \ No newline at end of file diff --git a/source/ruby/introspect.rst b/source/ruby/introspect.rst deleted file mode 100644 index b48d61de..00000000 --- a/source/ruby/introspect.rst +++ /dev/null @@ -1,35 +0,0 @@ -========== -Introspect -========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/introspect.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/introspect.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`introspect.rb` - * :ruby-better-explain:`introspect.rst` - - diff --git a/source/ruby/iterate_each.rst b/source/ruby/iterate_each.rst deleted file mode 100644 index c062b35d..00000000 --- a/source/ruby/iterate_each.rst +++ /dev/null @@ -1,35 +0,0 @@ -============ -Iterate Each -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/iterate_each.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/iterate_each.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`iterate_each.rb` - * :ruby-better-explain:`iterate_each.rst` - - diff --git a/source/ruby/kernel_method.rst b/source/ruby/kernel_method.rst deleted file mode 100644 index 172a8161..00000000 --- a/source/ruby/kernel_method.rst +++ /dev/null @@ -1,35 +0,0 @@ -============= -Kernel Method -============= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/kernel_method.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/kernel_method.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`kernel_method.rb` - * :ruby-better-explain:`kernel_method.rst` - - diff --git a/source/ruby/module_mixin.rst b/source/ruby/module_mixin.rst deleted file mode 100644 index 5c3f6439..00000000 --- a/source/ruby/module_mixin.rst +++ /dev/null @@ -1,33 +0,0 @@ -============ -Module Mixin -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/module_mixin.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/module_mixin.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`module_mixin.rb` - * :ruby-better-explain:`module_mixin.rst` diff --git a/source/ruby/modules_with_methods.rst b/source/ruby/modules_with_methods.rst deleted file mode 100644 index 3294027f..00000000 --- a/source/ruby/modules_with_methods.rst +++ /dev/null @@ -1,35 +0,0 @@ -==================== -Modules With Methods -==================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/modules_with_methods.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/modules_with_methods.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`modules_with_methods.rb` - * :ruby-better-explain:`modules_with_methods.rst` - - diff --git a/source/ruby/open_url.rst b/source/ruby/open_url.rst deleted file mode 100644 index 79ea258d..00000000 --- a/source/ruby/open_url.rst +++ /dev/null @@ -1,35 +0,0 @@ -======== -Open URL -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/open_url.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/open_url.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`open_url.rb` - * :ruby-better-explain:`open_url.rst` - - diff --git a/source/ruby/puts_examples.rst b/source/ruby/puts_examples.rst deleted file mode 100644 index 484000fc..00000000 --- a/source/ruby/puts_examples.rst +++ /dev/null @@ -1,35 +0,0 @@ -============= -Puts Examples -============= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/puts_examples.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/puts_examples.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`puts_examples.rb` - * :ruby-better-explain:`puts_examples.rst` - - diff --git a/source/ruby/puts_functionname.rst b/source/ruby/puts_functionname.rst deleted file mode 100644 index 550903af..00000000 --- a/source/ruby/puts_functionname.rst +++ /dev/null @@ -1,35 +0,0 @@ -================= -Puts Functionname -================= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/puts_functionname.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/puts_functionname.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`puts_functionname.rb` - * :ruby-better-explain:`puts_functionname.rst` - - diff --git a/source/ruby/require_stmt.rst b/source/ruby/require_stmt.rst deleted file mode 100644 index 908ea516..00000000 --- a/source/ruby/require_stmt.rst +++ /dev/null @@ -1,35 +0,0 @@ -================= -Require Statement -================= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/require_stmt.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/require_stmt.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`require_stmt.rb` - * :ruby-better-explain:`require_stmt.rst` - - diff --git a/source/ruby/ruby13.rst b/source/ruby/ruby13.rst deleted file mode 100644 index 662042f7..00000000 --- a/source/ruby/ruby13.rst +++ /dev/null @@ -1,35 +0,0 @@ -====== -Ruby13 -====== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/ruby13.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/ruby13.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`ruby13.rb` - * :ruby-better-explain:`ruby13.rst` - - diff --git a/source/ruby/ruby16.rst b/source/ruby/ruby16.rst deleted file mode 100644 index 9f801fab..00000000 --- a/source/ruby/ruby16.rst +++ /dev/null @@ -1,35 +0,0 @@ -====== -Ruby16 -====== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/ruby16.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/ruby16.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`ruby16.rb` - * :ruby-better-explain:`ruby16.rst` - - diff --git a/source/ruby/ruby5.rst b/source/ruby/ruby5.rst deleted file mode 100644 index b510ff56..00000000 --- a/source/ruby/ruby5.rst +++ /dev/null @@ -1,35 +0,0 @@ -===== -Ruby5 -===== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/ruby5.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/ruby5.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`ruby5.rb` - * :ruby-better-explain:`ruby5.rst` - - diff --git a/source/ruby/ruby7.rst b/source/ruby/ruby7.rst deleted file mode 100644 index 9971d473..00000000 --- a/source/ruby/ruby7.rst +++ /dev/null @@ -1,35 +0,0 @@ -===== -Ruby7 -===== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/ruby7.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/ruby7.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`ruby7.rb` - * :ruby-better-explain:`ruby7.rst` - - diff --git a/source/ruby/ruby_function.rst b/source/ruby/ruby_function.rst deleted file mode 100644 index 2da91288..00000000 --- a/source/ruby/ruby_function.rst +++ /dev/null @@ -1,35 +0,0 @@ -============= -Ruby Function -============= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/ruby_function.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/ruby_function.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`ruby_function.rb` - * :ruby-better-explain:`ruby_function.rst` - - diff --git a/source/ruby/see_backtrace.rst b/source/ruby/see_backtrace.rst deleted file mode 100644 index 7083cf68..00000000 --- a/source/ruby/see_backtrace.rst +++ /dev/null @@ -1,35 +0,0 @@ -============== -See Back Trace -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/see_backtrace.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/see_backtrace.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`see_backtrace.rb` - * :ruby-better-explain:`see_backtrace.rst` - - diff --git a/source/ruby/simpleNumber.rst b/source/ruby/simpleNumber.rst deleted file mode 100644 index 7e21db6d..00000000 --- a/source/ruby/simpleNumber.rst +++ /dev/null @@ -1,35 +0,0 @@ -============= -Simple Number -============= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/simpleNumber.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/simpleNumber.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`simpleNumber.rb` - * :ruby-better-explain:`simpleNumber.rst` - - diff --git a/source/ruby/string_methods.rst b/source/ruby/string_methods.rst deleted file mode 100644 index f948614a..00000000 --- a/source/ruby/string_methods.rst +++ /dev/null @@ -1,35 +0,0 @@ -============== -String Methods -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/string_methods.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/string_methods.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`string_methods.rb` - * :ruby-better-explain:`string_methods.rst` - - diff --git a/source/ruby/string_templates.rst b/source/ruby/string_templates.rst deleted file mode 100644 index 28bd516e..00000000 --- a/source/ruby/string_templates.rst +++ /dev/null @@ -1,35 +0,0 @@ -================ -String Templates -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/string_templates.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/string_templates.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`string_templates.rb` - * :ruby-better-explain:`string_templates.rst` - - diff --git a/source/ruby/string_times.rst b/source/ruby/string_times.rst deleted file mode 100644 index d2f94549..00000000 --- a/source/ruby/string_times.rst +++ /dev/null @@ -1,35 +0,0 @@ -============ -String Times -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/string_times.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/string_times.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`string_times.rb` - * :ruby-better-explain:`string_times.rst` - - diff --git a/source/ruby/tc_simpleNumber.rst b/source/ruby/tc_simpleNumber.rst deleted file mode 100644 index fd4729b1..00000000 --- a/source/ruby/tc_simpleNumber.rst +++ /dev/null @@ -1,35 +0,0 @@ -================ -Tc Simple Number -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/tc_simpleNumber.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/tc_simpleNumber.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :ruby-suggest-improve:`tc_simpleNumber.rb` - * :ruby-better-explain:`tc_simpleNumber.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 dda54254..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/go_template.rst b/utils/go_template.rst deleted file mode 100644 index 15798173..00000000 --- a/utils/go_template.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Section Name -============ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/go/PROGRAMNAME.go - :language: go - :tab-width: 4 - -.. runcode:: ../../languages/go/PROGRAMNAME.go - :language: go - :codesite: ideone - -Explanation -=========== - - - - -.. git_changelog:: - - -.. seealso:: - - * :go-suggest-improve:`PROGRAMNAME.go` - * :go-better-explain:`PROGRAMNAME.rst` - diff --git a/utils/java_template.rst b/utils/java_template.rst deleted file mode 100644 index df64bf9f..00000000 --- a/utils/java_template.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Section Name -============ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/java/PROGRAMNAME.java - :language: java - :tab-width: 4 - -.. runcode:: ../../languages/java/PROGRAMNAME.java - :language: java - :codesite: ideone - -Explanation -=========== - - - - -.. git_changelog:: - - -.. seealso:: - - * :java-suggest-improve:`PROGRAMNAME.java` - * :java-better-explain:`PROGRAMNAME.rst` - diff --git a/utils/python_template.rst b/utils/python_template.rst deleted file mode 100644 index bd1ece52..00000000 --- a/utils/python_template.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Section Name -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/PROGRAMNAME.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/PROGRAMNAME.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - -.. git_changelog:: - - -.. seealso:: - - * :python-suggest-improve:`PROGRAMNAME.py` - * :python-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 diff --git a/utils/ruby_template.rst b/utils/ruby_template.rst deleted file mode 100644 index 9231eb45..00000000 --- a/utils/ruby_template.rst +++ /dev/null @@ -1,35 +0,0 @@ -============ -Section Name -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/ruby/PROGRAMNAME.rb - :language: ruby - :tab-width: 4 - -.. runcode:: ../../languages/ruby/PROGRAMNAME.rb - :language: ruby - :codesite: ideone - -Explanation -=========== - - - - -.. git_changelog:: - - -.. seealso:: - - * :ruby-suggest-improve:`PROGRAMNAME.rb` - * :ruby-better-explain:`PROGRAMNAME.rst` - - diff --git a/utils/scala_template.rst b/utils/scala_template.rst deleted file mode 100644 index fc90ef77..00000000 --- a/utils/scala_template.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Section Name -============ - -Question -======== - -ADDQUESTION - -Solution -======== - -.. literalinclude:: ../../languages/scala/PROGRAMNAME.scala - :language: scala - :tab-width: 4 - -.. runcode:: ../../languages/scala/PROGRAMNAME.scala - :language: scala - :codesite: ideone - -Explanation -=========== - - - - -.. git_changelog:: - - -.. seealso:: - - * :scala-suggest-improve:`PROGRAMNAME.scala` - * :scala-better-explain:`PROGRAMNAME.rst` -