Vision and dreams are the blueprints of soul and achievements.
-Mohammed Ahmed F

Showing posts with label C Program. Show all posts
Showing posts with label C Program. Show all posts
Importance of "C" Language

Importance of "C" Language

Folks,

Strange thing happened today:

Today, a pre-final year student asked me:

"Sir, my teacher told me that C is an out-dated language. Nobody works on C. Then why do you teach such an out-dated language?".

I was initially shocked to hear this and later explained him the importance of C Programming language. C can never be out-dated. C still remains the widely used programming language on earth. I have heard from Tech-Managers that, they are finding very difficult to find good C programmers and there are not many FRESHERS who choose it. Now, I get to know the reason behind it. There are people without general knowledge who misguide students about something that they don't know.

C is one of the most powerful language used for System Programming. Programming with C is fun and you should really be lucky enough to work as a C Programmer. If you would like to know the usage of C, then download the source code of Linux Kernel from www.kernel.org and browse through the source code directories. You will enjoy it a lot.

The below link says that, C still remains the most popular language compared to other programming languages. You can have a look!

http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

-Chief Administrative Officer.
True programmer can understand this!

True programmer can understand this!

Folks,

Do you feel miserable as a programmer?

1. Constantly compare yourself to other programmers.

2. Talk to your family about what you do and expect them to cheer you up.

3. Base the success of your career on one project.

4. Stick with what you know.

5. Recode from scratch that already exists and works.

6. Expect that your code will be more efficient.

7. Try to learn a new programming language and fail.

8. Count your build errors.

9. Never Debug.

10. Set unachievable / overwhelming goals to be achieved by tomorrow.

-Chief Administrative Officer.
5 common problems a new programmer faces?

5 common problems a new programmer faces?

Folks,

The 5 Most Common Problems New Programmers Face--And How You Can Solve Them
Getting set up

Learning to program is hard enough, but it's easy to get tripped up before you even begin. First you need to chose a programming language (I recommend C++), then You need a compiler and a programming tutorial that covers the language you chose and that works with the compiler that you set up. This is all very complicated, and all before you even start to get to the fun parts. 

If you're still struggling with getting the initial setup, then check out our page on setting up a compiler and development environment (Code::Blocks and MINGW) which walks you through setting up a compiler with a lot of screenshots, and gets you up to the point of having an actual running program.

Thinking Like a Programmer

Have you seen the State Farm commercials where the car wash company returns the cars to customers with the soap suds still on the car? The company washes the car, but it didn't rinse it. 

This is a perfect metaphor for computer programs. Computers, like that car wash company, are very very literal. They do exactly, and only, what you tell them to do; they do not understand implicit intentions. The level of detail required can be daunting at first because it requires thinking through every single step of the process, making sure that no steps are missing. 

This can make programming seem to be a tough slog at first, but don't despair. Not everything must be specified--only what is not something the computer can already do. The header files and libraries that come with your compiler (for example, the iostream header file that allows you to interact with the user) provide a lot of pre-existing functionality. You can use websites like http://www.cppreference.com or our own function reference to find information on these pre-existing libraries of functionality. By using these, you can focus on precisely specifying only what is unique about your program. And even once you do that, you will begin to see patterns that can be turned into functions that wrap up a bunch of steps into a single function that you can call from everywhere. Suddenly complex problems will begin to look simple. It's the difference between:


Walk forward ten feet
Move your hand to the wall
Move your hand to the right until you hit an obstacle
...
Press upward on indentation and Walk to door Find light switch Turn on light.

The magic thing about programming is that you can box up a complex behaviour into a simple subroutine (often, into a function) that you can reuse. Sometimes it's hard to get the subroutine done up just right at first, but once you've got it, you no longer need to worry about it. 

You can go here to read more about how to think about programming, written for beginners.


Compiler Error Messages


This may seem like a small thing, but because most beginners aren't familiar with the strictness of the format of the program (the syntax), beginners tend to run into lots of complaints generated by the compiler. Compiler errors are notoriously cryptic and verbose, and by no means were written with newbies in mind. 

That said, there are a few basic principles you can use to navigate the thicket of messages. First, often times a single error causes the compiler to get so confused that it generates dozens of messages--always start with the first error message. Second, the line number is a lie. Well, maybe not a lie, but you can't trust it completely. The compiler complains when it first realizes there is a problem, not at the point where the problem actually occurred. However, the line number does indicate the last possible line where the error could have occurred--the real error may be earlier, but it will never be later. 

Finally, have hope! You'll eventually get really really good at figuring out what the compiler actually means. There will be a few error messages that today seem completely cryptic, even once you know what the real problem was, that in a few months time you will know like an old (if confused) friend. I've actually written more about this in the past; if you want more detailed help, check out my article on deciphering compiler and linker errors. (Interested in learning how to deal with these errors and other programming problems in a more guided way? Consider taking a course in computer science with our sponsor, Creighton online.)


Debugging


Debugging is a critical skill, but most people aren't born with a mastery of it. Debugging is hard for a few reasons; first, it's frustrating. You just wrote a bunch of code, and it doesn't work even though you're pretty sure it should. Damn! Second, it can be tedious; debugging often requires a lot of effort to narrow in on the problem, and until you have some practice, it can be hard to efficiently narrow it down. One type of problem, segmentation faults, are a particularly good example of this--many programmers try to narrow in on the problem by adding in print statements to show how far the program gets before crashing, even though the debugger can tell them exactly where the problem occurred. Which actually leads to the last problem--debuggers are yet another confused, difficult to set up tool, just like the compiler. If all you want is your program to work, the last thing you want to do is go set up ANOTHER tool just to find out why. 

To learn more about debugging techniques, check out this article on debugging strategies.


Designing a Program


When you're just starting to program, design is a real challenge. Knowing how to think about programming is one piece, but the other piece is knowing how to put programs together in a way that makes it easy to modify them later. Ideas like "commenting your code", "encapsulation and data hiding" and "inheritance" don't really mean anything when you haven't felt the pain of not having them. The problem is that program design is all about making things easier for your future self--sort of like eating your vegetables. Bad designs make your program inflexible to future changes, or impossible to understand after you've written. Frequently, bad design exposes too many details of how something is implemented, so that every part of the program has to know all the details of each other section of the program.

One great example is writing a checkers game. You need some way to represent the board--so you pick one. A fixed-sized global array: int checkers_board[8][8]. Your accesses to the board all go directly through the array: checkers_board[x][y] = ....; Is there anything wrong with this approach? You betcha. Notice that I wrote your accesses to the board all go directly through the array. The board is the conceptual entity--the thing you care about. The array happens to be, at this particular moment, how you implement the board. Again, two things: the thing you represent, and the way you represent it. By making all accesses to the board use the array directly, you entangle the two concepts. What happens when you decide to change the way you represent the board? You have an awful lot of code to change. But what's the solution? 

If you create a function that performs the types of basic operations you perform on the checkers board (perhaps a get_piece_on_square() method and a set_piece_to_square() method), every access to the board can go through this interface. If you change the implementation, the interface is the same. And that's what people mean when they talk about "encapsulation" and "data hiding". Many aspects of program design, such as inheritance, are there to allow you to hide the details of an implementation (the array) of a particular interface or concept (the board).
Reverse all words but not the string using pointer

Reverse all words but not the string using pointer

To write a C program to accept a string from the user and reverse all words but not the string using pointer.

String: sihT sI A dooG golB
Result: This Is A Good Blog


Solution:-

//C program for reverse all words but not the string using pointer

‪#‎include‬<stdio.h>
#include<conio.h>
int main()
{
char str[30];
char *p,*tmp;
printf("Enter any string: ");
gets(str);
for(p=str; *p!='\0'; p++)
{
if(*(p+1)==' ' || *(p+1)=='\0')
{
for(tmp=p; *tmp!=' ' && tmp>=str; tmp--)
printf("%c",*tmp);
}
printf(" ");
}
getch();
return 0;
}

Debugging Tips

Folks,

From the Chief Administrative Officer's desk:-


"Earlier, debugging tips was in an exclusive page but now it has been given in a post so as not to limit exceed the page limits set by Blogger for each blog, this (http://bca-tnc.blogspot.com/) is one blog!


The actual debugging tips page which was published on 19 / 02 / 2014, received 75 pageviews + 1 comment as "Nice.. Tnx" by an Anonymous.


Hence, it is brought to the kind notice of the readers that henceforth, the page views generated for this post will be considered 75 + {pageViewed} under the account of Chief Administrative Officer which is nothing but the Administrator Console."





Here is your Debugging Tips:-




You are never too old to learn something stupid. You can go too slowly as well as too fast.

Don't avoid a topic after you have mastered everything in it. By facing more challenging ideas, it will help cement grasp of the basics.


1. Look at the example code:

Reading is usually about the words on the page, but learning to program is about Code. When you are first learning to program, you should make sure to look at and try to understand each and every example carefully and understand them. If you are unable to understand then try asking someone who has expertise in it, remember ‘Lesson repeat itself unless they are read”.

When I first learned to program, I would sometimes read the code examples before the text, and try to figure out how it worked. It doesn't always work, but it did force me to look at the example very carefully and at times it often helped make the concept clear.

2. Don't just read example codes but run them:

But when you are reading a programming book, it is easy to look at the sample code and say "I get it that makes sense". Of course, you might get it, but you might not get it, and you just don't know it. There is only one way to find out to do something with that code. Then type the sample code into a compiler, if you type it, instead of copying and pasting it, you will really force yourself to go through everything that is there. Typing the code will force you to pay attention to the details of the syntax of the language, things like those funny semicolons that seem to go after every line.

Then compile it and run it. Make sure it does what you think it does. Then change it. Software is the most easily changeable machinery available on the planet. You can experiment easily, try new things, see what happens, the changes will happen almost immediately. The easiest way to learn new language features is to take some code that works one way and change it to the other.


3. Write your own code as soon as possible:

Once you understand something about the language or even if you are still getting your head around it, start writing simple programs that use it.

Sometimes it is hard to find good ideas for what programs to write. That's OK; you don't have to come up with every idea at the beginning. You can find some programming challenges on this site.

You can also re-implement the examples from the book you are reading. Try to do so without looking back at the sample code; it won't be as easy as it seems. This technique can work especially well if you tweak the sample code. If you can't think of a small program to write, but you have in mind a larger program you want to implement, like a game, you could start building small pieces that you can later use for a game. Whether you use them later or not, you will get the same useful experience.


4. Learn to use a debugger:

The sooner you learn debugging, easier it will be to learn to program. The first step in doing so is to learn how to use a tool called a debugger which allows you to step through your code. A debugger will allow you to step line by line through a piece of code. It will let you see the values of variables and whether the code inside an "if" statement is executed.

A debugger can help you quickly answer questions about what your code is doing.

int main()
{
        int x;
        int y;
        if( x > 4 )  // What is the value of x here?
        {
                y = 5;   // Did this line of code execute?
        }
}

A final word about debuggers, the first time you learn about a debugger, it will take you longer to fix the problems with your code. After the tenth or so bug, it will really start to pay off.

And believe me, you will have way more than ten bugs in your programming career.
I often saw students unwilling to use a debugger.

These students really made life hard on themselves, taking ages to find very simple bugs. The sooner you learn to use a debugger, the sooner it will pay off.


5. Seek out more sources:

If you don't understand something, there's a good possibility the way it was explained just didn't click. First, look for alternative explanations. The internet and this blog are filled with information about programming, and some explanations work better for different people; you might need pictures, someone else might not. There are also lots of good books with detailed explanations.

But if that does not work, the easiest way to figure out where your misunderstanding lies is to ask someone else. But try to go beyond saying, "I don't understand. Please explain". You are likely to get a link back to the same text you did not understand. Instead, rephrase your understanding of the text in your words.

The more your question reveals about what you are thinking, the easier it will be for a knowledgeable expert to answer it.

Programmers sometimes have a reputation for being grumpy about answering questions, but I think the reason is that they want to make progress in a conversation, and that requires both sides to put in effort. If you ask a smart, detailed question that shows you are thinking, you will generally get good results.


Happy coding.


-Chief Administrative Officer.
Program to print Diamond pattern

Program to print Diamond pattern

#include <stdio.h>
int main()
{
  int n, c, k, space = 1;

  printf("Enter number of rows\n");
  scanf("%d", &n);

  space = n - 1;
  for (k = 1; k <= n; k++)
  {
    for (c = 1; c <= space; c++)
      printf(" ");

    space--;
    for (c = 1; c <= 2*k-1; c++)
      printf("*");

    printf("\n");
  }

  space = 1;
  for (k = 1; k <= n - 1; k++)
  {
    for (c = 1; c <= space; c++)
      printf(" ");

    space++;
    for (c = 1 ; c <= 2*(n-k)-1; c++)
      printf("*");

    printf("\n");
  }

  return 0;
}
Palindrome

Palindrome

 #include<stdio.h> 
  #include <string.h>
  main() 
  { 
     char a[100], b[100]; 
     printf("Enter the string to check if it is a palindrome\n"); 
     gets(a); 
     strcpy(b,a); 
     strrev(b); 
     if( strcmp(a,b) == 0 ) 
       printf("Entered string is a palindrome.\n"); 
      else 
       printf("Entered string is not a palindrome.\n"); 
       return 0; 
  }
Sample Linked list program

Sample Linked list program

#include < stdio.h>
#include < stdlib.h>
struct NODE 
{
int number;
struct NODE *next;
};
int search_value(struct NODE *llist, int num);
void append_node(struct NODE *llist, int num);
void display_list(struct NODE *llist);
void delete_node(struct NODE *llist, int num);
int main(void) 
{
int num = 0;
int input = 1;
int retval = 0;
struct NODE *llist;
llist = (struct NODE *)malloc(sizeof(struct NODE));
llist->number = 0;
llist->next = NULL;
while(input != 0) 
{
printf("\n-- Menu Selection --\n");
printf("0) Quit\n");
printf("1) Insert\n");
printf("2) Delete\n");
printf("3) Search\n");
printf("4) Display\n");
scanf("%d", &input);
switch(input) 
{
case 0: 
default:
printf("Goodbye ...\n");
input = 0;
break;
case 1:
printf("Your choice: `Insertion'\n");
printf("Enter the value which should be inserted: ");
scanf("%d", &num);
append_node(llist, num);
break;
case 2:
printf("Your choice: `Deletion'\n");
printf("Enter the value which should be deleted: ");
scanf("%d", &num);
delete_node(llist, num);
break;
case 3:
printf("Your choice: `Search'\n");
printf("Enter the value you want to find: ");
scanf("%d", &num);
if((retval = search_value(llist, num)) == -1)
printf("Value `%d' not found\n", num);
else
printf("Value `%d' located at position `%d'\n", num, retval);
break;
case 4:
printf("You choice: `Display'\n");
display_list(llist);
break;
} /* switch */
} /* while */
free(llist);
return(0);
}
void display_list(struct NODE *llist) 
{
while(llist->next != NULL) 
{
printf("%d ", llist->number);
llist = llist->next;
}
printf("%d", llist->number);
}
void append_node(struct NODE *llist, int num) 
{
while(llist->next != NULL)
llist = llist->next;
llist->next = (struct NODE *)malloc(sizeof(struct NODE));
llist->next->number = num;
llist->next->next = NULL;
}
void delete_node(struct NODE *llist, int num) 
{
struct NODE *temp;
temp = (struct NODE *)malloc(sizeof(struct NODE));
if(llist->number == num) 
{
/* remove the node */
temp = llist->next;
free(llist);
llist = temp;
else 
{
while(llist->next->number != num)
llist = llist->next;
temp = llist->next->next;
free(llist->next);
llist->next = temp;
}
int search_value(struct NODE *llist, int num) 
{
int retval = -1;
int i = 1;
while(llist->next != NULL) 
{
if(llist->next->number == num)
return i;
else
i++;
llist = llist->next;
}
return retval;
}
Largest among n digit

Largest among n digit

    #include<stdio.h> 
    #include<conio.h> 
    void main() 
    { 
      int max_num(int a[],int n); 
      int max,i,n; 
      int a[50]; 
      clrscr(); 
      printf("Enter n number:"); 
      scanf("%d",&n); 
      printf("Enter the numbers:"); 
      for(i=0;i<n;i++) 
      scanf("%d",&a[i]); 
      max=max_num(a,n); 
      printf("The largest number is %d",max); 
      getch(); 
   } 
    int max_num(int a[],int n) 
    { 
      int i,m=0; 
      for(i=0;i<n;i++) 
      { 
        if(a[i]>m) 
          m=a[i]; 
      } 
      return m; 
   }
Counting Frequencies of Elements in an Array

Counting Frequencies of Elements in an Array

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define S 6
main()
   {
     int a[S], freq[S];
     int i, j, k,n = S;
     clrscr();
     for(i = 0; i < S; i++)
     {
       printf(" \n Enter a[%d] element: ", i);
       scanf(" %d ", &a[i]);
       freq[i] = 1;
     }
     printf(" Original Array\n ");
     for(i = 0; i < S; i++)
     printf(" %d   ", a[i]);
     /* Main Logic Starts Here */
     for(i = 0; i < n; i++)
     for(j = i + 1; j < n; j++)
     {
       if(a[i] == a[j])
       {
         for(k = j; k < n; k++)
         a[k] = a[k+1];
         freq[i]++;
         n--;
       }
     }
     printf(" \nArray with freq\n ");
     printf(" \nElement  Freq\n ");
     for(i = 0; i < n; i++)
     printf("%d  %d\n ", a[i], freq[i]);
     getch();
   }
Factorial

Factorial

  #include <stdio.h> 
  #include <conio.h> 
  long int factorial(int n); 
  void main() 
  { 
     int n; 
     clrscr(); 
     printf("Enter the number:\n"); 
     scanf("%d",&n); 
     printf("Factorial of %d is %ld",n,factorial(n)); 
     getch(); 
  } 
  long int factorial(int n) 
  { 
     if(n<=1) 
     { 
        return(01); 
     } 
     else 
     { 
        n=n*factorial(n-1); 
        return(n); 
     } 
  }
Program to reverse any number

Program to reverse any number

#include<stdio.h>
int main()
{
    int num,r,reverse=0;
 
    printf("Enter any number: ");
    scanf("%d",&num);
 
    while(num){
         r=num%10;
         reverse=reverse*10+r;
         num=num/10;
    }
 
    printf("\nReversed of number: %d",reverse);
    return 0;
}


Output:

Enter any number: 375
Reversed of number: 573
Introduction to Union

Introduction to Union

Union

A union is a special data type available in C that enables you to store different data types in the same memory location.

You can define a union with many members, but only one member can contain a value at any given time.

Unions provide an efficient way of using the same memory location for multi-purpose.

Defining a Union

To define a union, you must use the union statement in very similar was as you did while defining structure.

The union statement defines a new data type, with more than one member for your program.

The format of the union statement is as follows:

union [union tag]

{
member definition;
member definition;
...
member definition;
} [one or more union variables];


The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition.

At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional.

Here is the way you would define a union type named Data which has the three members i, f, and str:

union Data

{
int i;
float f;
char str[20];
} data;


Now a variable of Data type can store an integer, a floating-point number, or a string of characters.

This means that a single variable ie. same memory location can be used to store multiple types of data.

You can use any built-in or user defined data types inside a union based on your requirement.
Introduction File Input / Output

Introduction File Input / Output

File I/O

A file represents a sequence of bytes, does not matter if it is a text file or binary file.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file, this call will initialize an object of the type FILE, which contains all the information necessary to control the stream.

Following is the prototype of this function call:

FILE *fopen( const char * filename, const char * mode );

Here filename is string literal which you will use to name your file and access mode can have one of the following values:

ModeDescription

r Opens an existing text file for reading purpose.

w Opens a text file for writing, if it does not exist then a new file is created.

Here your program will start writing content from the beginning of the file.

a Opens a text file for writing in appending mode, if it does not exist then a new file is created.

Here your program will start appending content in the existing file content.

r+ Opens a text file for reading and writing both.

w+ Opens a text file for reading and writing both.

It first truncate the file to zero length if it exists otherwise create the file if it does not exist.

a+ Opens a text file for reading and writing both. It creates the file if it does not exist.

The reading will start from the beginning but writing can only be appended.

If you are going to handle binary files then you will use below mentioned access modes instead of the above mentioned:

"rb", "wb", "ab", "ab+", "a+b", "wb+", "w+b", "ab+", "a+b"

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is:
int fclose( FILE *fp );

The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function actually, flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.

There are various functions provide by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see few of the in the next section.

Writing a File

Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error.

You can use the following functions to write a null-terminated string to a stream:

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error.

You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.

Try the following example:

#include < stdio.h >
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions.

Reading a File

Following is the simplest function to read a single character from a file:

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error it returns EOF.

The following functions allow you to read a string from a stream:
char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
Program to find the strong number

Program to find the strong number

Strong Number
  void strong_number() 
  { 
    int num,i,p,r,sum=0,save_num; 
    printf("\n Enter a number:\t"); 
    scanf("%d",&num); 
    save_num=num; 
    while(num) 
    { 
        i=1,p=1; 
        r=num%10; 
    while(i<=r) 
      { 
        p=p*i; 
        i++; 
      } //while 
        sum=sum+p; 
        num=num/10; 
    } //while 
    if(sum==save_num) 
      printf("%d is a Strong number", save_num); 
    else 
      printf("%d is not a Strong number", save_num); 
  }


Output:

Enter a number:        153
153 is not a Strong number