Tuesday, 21 June 2016

Draw a Circle : Mid-Point Algorithm



C Program

  1. #include<graphics.h>
  2. #include<conio.h>
  3. #include<stdio.h>
  4. void plotpoints(int x, int y, int cx, int cy) {
  5. putpixel(cx + x, cy + y, 4);
  6. putpixel(cx - x, cy + y, 4);
  7. putpixel(cx + x, cy - y, 4);
  8. putpixel(cx - x, cy - y, 4);
  9. putpixel(cx + y, cy + x, 4);
  10. putpixel(cx - y, cy + x, 4);
  11. putpixel(cx + y, cy - x, 4);
  12. putpixel(cx - y, cy - x, 4);
  13. }
  14. void main() {
  15. int cx, cy, x = 0, y, r, p;
  16. int gd = DETECT, gm = DETECT;
  17. clrscr();
  18. printf("Enter the center \n");
  19. scanf("%d%d", &cx, &cy);
  20. printf("Enter the radius : ");
  21. scanf("%d", &r);
  22. y = r;
  23. p = 1 - r;
  24. initgraph(&gd, &gm, "");
  25. cleardevice();
  26. while (x < y) {
  27. plotpoints(x, y, cx, cy);
  28. x++;
  29. if (p < 0)
  30. p += 2 * x + 1; else {
  31. y--;
  32. p += 2 * (x - y) + 1;
  33. }
  34. }
  35. getch();
  36. }

Sunday, 19 June 2016

Files are needed in C...

Why files are needed?

When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created, these information can be accessed using few commands. 

There are large numbers of functions to handle file I/O in C language. In this tutorial, you will learn to handle standard I/O(High level file I/O functions) in C. 

High level file I/O functions can be categorized as:
  1. Text file
  2. Binary file



File Operations

  1. Creating a new file
  2. Opening an existing file
  3. Reading from and writing information to a file
  4. Closing a file

Working with file

While working with file, you need to declare a pointer of type file. This declaration is needed for communication between file and program.
FILE *ptr;

Opening a file

Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:
ptr=fopen("fileopen","mode")

For Example:
fopen("E:\\cprogram\program.txt","w"); 
  
/* --------------------------------------------------------- */
 E:\\cprogram\program.txt is the location to create file.   
 "w" represents the mode for writing.
/* --------------------------------------------------------- */
Here, the program.txt file is opened for writing mode.



Opening Modes in Standard I/O

File ModeMeaning of ModeDuring Inexistence of file
rOpen for reading.If the file does not exist, fopen() returns NULL.
wOpen for writing.If  the file exists, its contents are overwritten. If the file does not exist, it will be created.
aOpen for append. i.e, Data is added to end of file.If the file does not exists, it will be created.
r+Open for both reading and writing.If the file does not exist, fopen() returns NULL. 
w+Open for both reading and writing.If  the file exists, its contents are overwritten. If the file does not exist, it will be created.
a+Open for both reading and appending.If the file does not exists, it will be created.



Closing a File

The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose().
fclose(ptr); //ptr is the file pointer associated with file to be closed.

The Functions fprintf() and fscanf() functions.

The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure FILE 


Writing to a file

  1. #include <stdio.h>
  2. int main() {
  3. int n;
  4. FILE *fptr;
  5. fptr=fopen("C:\\program.txt","w");
  6. if(fptr==NULL) {
  7. printf("Error!");
  8. exit(1);
  9. }
  10. printf("Enter n: ");
  11. scanf("%d",&n);
  12. fprintf(fptr,"%d",n);
  13. fclose(fptr);
  14. return 0;
  15. }
This program takes the number from user and stores in file. After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open that file, you can see the integer you entered. Similarly, fscanf() can be used to read data from file. 


Reading from file

  1. #include <stdio.h>
  2. int main() {
  3. int n;
  4. FILE *fptr;
  5. if ((fptr=fopen("C:\\program.txt","r"))==NULL) {
  6. printf("Error! opening file");
  7. exit(1);
  8. /* Program exits if file pointer returns NULL. */
  9. }
  10. fscanf(fptr,"%d",&n);
  11. printf("Value of n=%d",n);
  12. fclose(fptr);
  13. return 0;
  14. }
If you have run program above to write in file successfully, you can get the integer back entered in that program using this program. Other functions like fgetchar(), fputc() etc. can be used in similar way. 


Binary Files

Depending upon the way file is opened for processing, a file is classified into text file and binary file. 

If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary file is used. 

Working of binary files is similar to text files with few differences in opening modes, reading from file and writing to file.

Opening modes of binary files

Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference between opening modes of text and binary files is that, b is appended to indicate that, it is binary file. 

Reading and writing of a binary file.

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files. 

Function fwrite() takes four arguments, address of data to be written in disk, size of data to be written in disk, number of such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above. 

Sunday, 12 June 2016

15 Free eBooks on C Programming

If we talk about the most used programming languages in electronics engineering, like Python, C is probably one of the most used language in electronics. So now its time for some free stuff on C Programming. Enjoy!

Author: Pieter Hartel, Henk Muller
Publisher: Addison-Wesley, 1999
The book teaches how to program in C, assuming that the student has already learnt how to formulate algorithms in a functional style. The student will become a better C programmer, capable of writing programs that are easier to maintain.
Author: K. Joseph Wesley, R. Rajesh Jeba Anbiah
Published in: 2008
This is an intermediate to advanced C programming book writen for C lovers, students, programmers, and other enthusiasts. The book is written to open many secrets of C, it also introduces various approaches to solve different problems.
Author: Zed A. Shaw
Publisher: LCodeTHW, 2011
A clear and direct introduction to modern C programming. The purpose of this book is to get you strong enough in C that you’ll be able to write your own software in it, or modify someone else’s code. The text is not for beginners.
Author: Bharat Kinariwala, Tep Dobry
Publisher: University of Hawaii at Manoa, 1993
Contents: Designing Programs Top Down; Processing Character Data; Numeric Data Types and Expression Evaluation; Pointers; Arrays; Functions and Files; Two Dimensional Arrays; Sorting and Searching; String Processing; Structures and Unions; etc.
Author: Axel-Tobias Schreiner
Published in: 1999
In this book, we are going to use ANSI-C to discover how object-oriented programming is done, what its techniques are, why they help us solve bigger problems, and how we harness generality and program to catch mistakes earlier.
Author: Harry McGeough
Publisher: Smashwords, 2011
Conceptive C is an AI programming Language based on Objective-C and C Language. It is a superset of both languages. Conceptive C uses concepts to program natural language and Artificial Intelligence based computer language based on Objective C.
Publisher: NeXT Software, Inc., 1996
Objective-C is implemented as set of extensions to the C language. This book both introduces the object-oriented model that Objective-C is based upon and fully documents the language. It concentrates on the Objective-C extensions to C.
Publisher: Wikibooks, 2006
C is the precursor for almost all of the popular high-level languages available today. This book represents a comprehensive look at the C programming language and its features. Basic computer literacy is assumed, but no special knowledge is needed.
Publisher: Wikibooks, 2010
This online wiki book is a quick and easy introduction to the ANSI C programming language. It is written by a novice, and is intended for use by a novice. However, it does assume some familiarity with a programming language.
Author: Al Aho, Jeff Ullman
Publisher: W. H. Freeman, 1994
Aho and Ullman have created a C version of their groundbreaking text. This book combines the theoretical foundations of computing with essential discrete mathematics. It follows the same organizations, with all examples and exercises in C.
Author: David Haskins
Publisher: BookBoon, 2009
Using a series of web development examples, this book will give you an interesting glimpse into a powerful lower-level world. C is tight and spare and economical, and people who know C will ensure critical systems keep running.
Author: Neil Smyth
Publisher: Techotopia, 2010
The Objective-C 2.0 Essentials free online book contains 34 chapters of detailed information intended to provide everything necessary to gain proficiency as an Objective-C programmer for both Mac OS X and iPhone development.
Author: Derek M. Jones
Publisher: Addison-Wesley Professional, 2008
The book about the latest version of the C Standard, it is a systematic analysis of the language standard. Every sentence in the C Standard appears in this book, followed by a commentary section, common implementations, coding guidelines, etc.
Author: Axel Schreiner, 2001
We use ANSI-C to find out how to write object oriented programs, what are they useful for solving bigger problems, and how to catch mistakes earlier. The book covers classes, objects, instances, inheritance, linkage, methods, polymorphisms, and more.
Author:Eric Huss, 1997
This guide provides a useful look at the standard C programming language. It will not teach one how to program in C, nor will it attempt to provide the history of C. It is merely a handy reference to the standard C library.

Thursday, 9 June 2016

C development on Linux - Coding style and recommendations - IX.

1. Translations

2. Introduction

You may wonder what is meant by the title. Code is code, right? It's important to be bug-free and that's that, what else? Development is more than writing code and testing/debugging it. Imagine you have to read someone else's work, and I suppose you already done that, and all the variables are named foo, bar, baz, var, etc. And the code isn't commented nor documented. You will probably feel the sudden urge to invoke unknown gods, then go to the local pub and drown your sorrows. They say that you should not do unto others what you don't want done unto you, so this part will focus of general coding guidelines, plus GNU-specific ideas that will help you have your code accepted. You are supposed to have read and understood the previous parts of this series, as well as solve all the exercises and, preferably, read and wrote as much code as possible.

3. Recommendations

Before starting, please take note of the actual meaning of the word above. I don't, in any way, want to tell you how to write your code, nor am I inventing these recommendations. These are the result of years of work by experienced programmers, and many will not just apply to C, but to other languages, interpreted or compiled.
I guess the first rule I want to stress out is: comment your code, then check if you commented enough, then comment some more. This is not beneficial for others that will read/use your code, but also for you. Be convinced that you will not remember what exactly you meant to write after two or three months, nor will you know what int ghrqa34; was supposed to mean, if anything. Good developers comment (almost) every line of their code as thoroughly as possible, and the payoff is more than you might realize at first, despite the increased time it takes to write the program. Another advantage is that by commenting, because this is how our brain works, whatever we wished to do will be better remembered, so again you won't look at your code, fast-forward a few months, wondering who wrote your code. Or why.
The C parser doesn't really care how ordered your code is. That means you can write a typical "Hello, world" program like this, and it would still compile:
#include <stdio.h> int main(){printf("Hello, world!"); return 0;}
It seems much more readable the way we wrote it the first time, doesn't it? The general rules regarding formatting are: one instruction per line , choose your tab width and be consistent with it, but make sure that it complies with the project's guidelines, if you're working on one, also make liberal use of blank lines, for delimiting various parts of the program, together with comments, and finally, although this is not necessarily coding style-related, before you start coding seriously, find an editor you like and learn to use it well. We will soon publish an article on editors, but until then Google will help you with some alternatives. If you hear people on forums, mailing lists, etc. saying "editor x sucks, editor y FTW!", ignore them. This is a very subjective matter and what's good for me might not be so good for you, so at least try some of the editors available for Linux for a few days each before even starting to try creating some opinion.
Be consistent in variable naming. Also make sure the names fit with the others, so there is harmony within the entire program. This applies even if you're the only author of the software, it will be easier to maintain later. Create a list of used prefixes and suffixes (e.g. max, min, get, set, is, cnt) and go with them, unless asked otherwise. Consistency is the key word here.

3.1. GNU-specific guidelines

What follows is a summary of the GNU coding standards , because we know you don't like to read such things. So if you're writing code that would like to fit into the GNU ecosystem, this is the document to read. Even if you don't, it's still a good read on how to write proper code.
This document is always worth a read in it's entirety if you are creating or maintaining GNU software, but you will find the most important parts below. One first issue worth mentioning is how to deal with function prototypes. Please go back to the part dealing with that if you have any issues. The idea is "if you have your own functions, use a prototype declaration before main(), then define the function when needed." Here's an example:
#include <stdio.h>

int func (int, int)

int main() 

[...]

int func (int x, int z)

[...]
Use proper and constant indentation. This cannot be emphasized enough. Experienced programmers with years and years of code behind will take it very badly when you submit code with improper indentation. In our case, the best way to get used to how GNU does this is by using GNU Emacs (although this is not in any form our way to tell you that "GNU Emacs is good for you, use it.", as we're proponents of free will and choice), where the default behaviour for C code is indentation set at two spaces and braces on a line for themselves. Which brings us to another important issue. Some people use braces like this:
while (var == 1) {
  code...
}
...while others, including GNU people, do it like this:
while (var == 1)
{
  code...
}
Of course, this also applies to conditional expressions, functions and every occasion where you need to use braces in C code. As far as noticed, this choice is something very GNU-specific, and how much of this you respect depends solely on your taste and stance on the issue.
Our next issue is a technical one, and a promise I had to keep: the malloc() issue. Besides writing pertinent and meaningful error messages, unlike the ones we've all seen in other operating systems, check that malloc() and friends always return zero. These are very serious issues, and you'll get a few words lesson about malloc() and when to use it. By now you know what allocating memory automatically or statically is. But these methods don't cover all bases. When you need to allocate memory and have more control over the operation, there's malloc() and friends, for dynamic allocation. Its' purpose is to allocate available memory from the heap, then the program uses the memory via a pointer that malloc() returns, then said memory must be free()d. And "must" is to be written with capitals in 2 feet letters with a burning red color. That's about it with malloc(), and the reasons have already been exposed earlier in the previous part.
You are urged to use a consistent interface in all your command-line programs. If you're already a seasoned GNU/Linux user you have noticed that almost all programs have --version and --help, plus, for example, -v for verbose, if such is the case. We'll not get into all of it here; grab a copy of the GNU Coding Standards, you will need it anyway.
Although I personally tend to overlook this, and to many it's a minor issue, it will improve the readability of your code, because, again, that's how our brain works. The idea is: when you're in doubt about using spaces, use them. For example:
int func (var1, var2);

int func(var1,var2);
There are some that say you can't avoid nested ifs. There are others that say "why avoid nested ifs?" And there are yet others that simply do not use nested ifs. You will create your own opinion on this as time passes and lines of code you write increase. The idea is, if you use them, make them as readable as humanly possible, as they easily can lead to almost-spaghetti code, hard to read and to maintain. And again, use comments.
The GNU coding standard say that it's good to have your code be as portable as can be, "but not paramount". Portable hardware-wise? That depends on the program's purpose and what machines you have at your disposal. We are referring more to the software side, namely portability between Unix systems, open source or not. Avoid ifdefs if you can, avoid assumptions regarding file locations (e.g. Solaris installs third-party software under /opt, while BSD and GNU/Linux do not), and generally aim for clean code. Speaking of assumptions, do not even assume that a byte is eight bits or that a CPU's address space must be an even number.
Documenting your code, in form of manual pages and well-written READMEs and so on, is another paramount aspect of software development. Yes, it IS a tedious task, but if you don't have a documentation writer on your team, it's your responsibility to do it, as every good programmer does his/her job from A to Z.

4. Conclusion

Next time we'll continue from where we left off here: going from idea to a complete program, with Makefiles, documentation, release cycles and all the fun stuff.