Showing posts with label C program. Show all posts
Showing posts with label C program. Show all posts

Tuesday, November 12, 2013

C program to find the Pythagorean prime!!

Below C program is to find the Pythagorean prime of a given number. If sum of the squares of any to numbers is prime number, then that number is called Pythagorean prime.

e.g
5 = 1*1 + 2*2.
13 = 2*2 + 3+3

All prime numbers are not pythagorean primes. for example 7. 7 is a prime number and not pythagorean prime. So to find the pythagorean prime, first we need to the given number is prime or not. If the given number is not prime, we can stop the process there itself.

#include<stdio.h>
int fact(int x)
{
 if(x==1)
 return 1;
 fact(x*(x-1));
}
int isPrime(int x)
{
 int i;
 for(i=2;i<x;i++)
 {
 if(x%i == 0)
 return 0i;
 }
 return 1;
}
int main()
{
 int number;
 int found = 0;
 int i=0,j=0;
 printf("enter the number\n");
 scanf("%d",&number);
 if(!isPrime(number)){
 printf("To find Pythagorean prime, number should be prime \n");
 return 0;
 }
 for(i=1;i<500;i++)
 {
 for(j=1;j<500;j++)
 {
 if(i*i+j*j==number)
 {
 found = 1;
 break;
 }
 }
 if(found)
 break;
 }
 if(found)
 printf("%d is Pythagorean prime\n",number);
 else 
 printf("%d is not Pythagorean prime\n",number);
}
Output:

$ ./a.out
enter the number
137
137 is Pythagorean prime
$ ./a.out
enter the number
23
23 is not Pythagorean prime
$ ./a.out
enter the number
1234
To find Pythagorean prime, number should be prime

Sunday, November 10, 2013

C programs Structure union bit-fields!!

In C Programming Language, a structure is a user defined data type, which is a collection of different data types. Strutures, unions and bitfields are conceptually same, the difference in memory alignment. So defferentiate them, we need to get the size of the structure or union. Below are the sample c programs for each of them. Structures also do padding, Click here to get how padding works.

For below examples, size of int is 4 bytes(some systems allocates 2 or 8. ) and character takes 1 byte.

Structures in C: Below structure is collection of one char and one int data types. So total size should be 5 bytes(1+4). Because of memory alignment, it will allocate 4 bytes for char also, but 3 of 4 bytes in char variable or unused. So we will get the size of the structure as 8.

#include&lt;stdio.h>
struct Sample{
 char c;
 int n;
};
int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}
Output:
$ ./a.out
size is 8

Unions in C: Unions are also same as structures. But the difference in memory alignment. The size of the union is the maximum size of the data type in the union. For example in the below example, union contains one char variable and one int variable, so char takes 1 byte and int takes 4 bytes, max of (1,4) is 4 , so size of the union is 4 bytes.

#include&lt;stdio.h>
union Sample{
 char c;
 int n;
};
int main()
{
 union Sample s;
 printf("size is %u\n",sizeof(s));
}
Output:
$ ./a.out
size is 4

Bit fields in C: In the structure example we have seen, 3 bytes are unused because of memory alignment and padding. So to avoid these unused bytes, bit fields are introduced. We can specify, required bits using bitfields as shown below. We need to use colon(:) after the variable name, and specify the number of bits.

In the below example, we specified 2 bits for char and 2 bits for int, so total 4 bits (and not bytes), total size should be 4 bits, but because of memory alignment and padding, we will get 4 bytes as shown below. We will get 4 bytes until all the bits in the 4 bytes (32 bits) are used.

#include&lt;stdio.h>
struct Sample{
 char c:2;
 int n:2;
};
int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}

Output:
$ ./a.out
size is 4

How structure padding works?

Structures in C programming language are collection of different data types. Click here for more details about structures. C compiler will structure padding for the structures in the memory alignment..

Why structure padding: Structure padding will be used for fast execution. Generally memory allocation will be done basing on the size of the int for the fast execution. So to achieve this rule, if the size of the memory space is less than the size of the int (for example char it takes 1 byte), padding will be done by adding required bytes.

Lets look at the below example: In the example, structure contains char (1byte) and int(4 bytes), so total size should be 5 bytes. But because of memory alignment for fast execution, compiler will be added extra 3 bytes as a padding, and the total size of the structure will be 8 bytes.

Sample C program for Structures:
#include<stdio.h>
struct Sample{
 char c;
 int n;
};
int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}

Output:
$ ./a.out
size is 8

Look at another example: In the below example we added extra char variable c2, still the size of the structure is same. Because char takes one byte and two chars are in sequential, so size is (1+1+2padding+4), so total size is 8 bytes.

#include<stdio.h>
struct Sample{
 char c1;
 char c2;
 int n;
};
int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}

Output:
$ ./a.out
size is 8

Look at another example: In the below example, we added the extra char c2 after the int variable and the size of the structure is now 12 bytes. This is also due to padding. char+int+char which is equal to 1+3(padding)+4+1+3(padding).

In the above example, two chars and int takes 8 bytes, but here two chars and int takes 12 bytes. This is because of order of the variables used in the structure. For structure padding, order of the variables are also very important.

So in the below example, first char 1byte and no chars are there after it, so 3bytes for padding, for int b bytes and for another char c2 one byte and 3 padding bytes. If another char is there after c2, only 2 bytes padding will be required.

#include<stdio.h>
struct Sample{
 char c1;
 int n;
 char c2;
}; int main() { struct Sample s; printf("size is %u\n",sizeof(s)); }

Output:
$ ./a.out
size is 12

Wednesday, November 6, 2013

finding square root of a number without using sqrt method!!


Below code is to find the square root of a given integer number with out using sqrt math library function. Its very simple and brute force way to find the square root. This is not the best way, but one of the way to find the square root. The basic Idea is to squaring the numbers from one and checking with the given number, if the given number is same the square of the number, then squared number is the square root of the number. If you need for more than 5000, jus modify the MAX_NUMBER in the code and run.


Limitations:

  • It works for only Integers
  • Its a brute force method


#include<stdio.h>
#define MAX_NUMBER 5000
int find_sqrt(int number)
{
 int i,product = 0;
 for(i=0;i<MAX_NUMBER;i++)
 {
 product = i*i;
 if(product==number)
 return i;
 else if(product>number)
 break;
 }
 return 0;
}
int main()
{
 int n=0,result=0;
 printf("enter the number to find the sqrt\n");
 scanf("%d",&n);
 if(n<0)
 {
 printf("enter only +ve integer value");
 return 0;
 }
 result = find_sqrt(n);
 if(result)
 printf("sqrt of %d is %d\n",n,result);
 else
 printf("not a proper value for finding the sqrt\n");
}
Output:


$ ./a.out
enter the number to find the sqrt
625
sqrt of 625 is 25

$ ./a.out
enter the number to find the sqrt
123
not a proper value for finding the sqrt

finding cube root of a number without pow method in C!!



Below code is to find the cube root of a given integer number with out using pow math library function. Its very simple and brute force way to find the cube root. This is not the best way, but one of the way to find the cube root. The basic Idea is to find the cube of the numbers from one and checking with the given number, if the given number is same the cube of the number, then cube number is the cube root of the number. If you need for more than 5000, jus modify the MAX_NUMBER in the code and run.


Limitations:

  • It works for only Integers
  • Its a brute force method


#include<stdio.h>
#define MAX_NUMBER 5000
int find_cuberoot(int number)
{
 int i,cube= 0;
 for(i=0;i<MAX_NUMBER;i++)
 {
 cube= i*i*i;
 if(cube==number)
 return i;
 else if(cube>number)
 break;
 }
 return 0;
}
int main()
{
 int n=0,result=0;
 printf("enter the number to find the cube root\n");
 scanf("%d",&n);
 if(n<0)
 {
 printf("enter only +ve integer value");
 return 0;
 }
 result = find_cuberoot(n);
 if(result)
 printf("cube root of %d is %d\n",n,result);
 else
 printf("not a proper value for finding the cube root\n");
}
Output:

$ ./a.out
enter the number to find the cube root
15625
cube root of 15625 is 25
$ ./a.out
enter the number to find the cube root
99
not a proper value for finding the cube root

Tuesday, November 5, 2013

Bit Fiddling !!

Bit fields are one of the most important aspects of embedded programming . Let us see few tricky and interesting cases in that field .. 1. Searching for the no of bits set in a given number -- Let us see with an example how we can check for the no of bits set in a number
#include<stdio.h>
#include<sys/time.h>
#include<string.h>
#include<time.h>
char *time_stamp()
{
 static char buf[100];
 char timestamp[100];
 time_t time;
 struct timeval detail_time;
 memset (buf, 0, 100);
 gettimeofday(&detail_time,NULL);
 time = detail_time.tv_sec;
 strftime(timestamp, 100, "%Y/%m/%d %H:%M:%S", localtime(&time));
 sprintf(buf, "%s:%ld:%ld ", timestamp,
 detail_time.tv_usec /1000, detail_time.tv_usec%1000);
 
 return buf;
}
int main()
{
int test ;
int temp,i=0;
char bits_count= 0;
printf("Enter any number \n");
scanf("%d",&test);
temp =test;
printf("Time stamp 1 is %s \n",time_stamp());
/* Method -1 */
do {
if(temp & 1)
 bits_count++;
temp = temp >>1;
}while((i++)<(sizeof(int)*8));
printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 2 is %s \n",time_stamp());
bits_count= 0;
temp =test;
/* Method - 2*/
while(temp)
{ 
 if(temp & 1)
 bits_count++;
 temp =temp >>1;
};
printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 3 is %s \n",time_stamp());
/*Method -3 */
bits_count= 0;
temp =test;
while(temp)
{ 
 if(!((char)temp & 0xff))
 temp = temp >> 8;
 else if(temp & 1)
 bits_count++;
 temp =temp >>1;
};
printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 4 is %s \n",time_stamp());
return 0 ;
}
Enter any number 32 <<< one of the worst case scenarios ! Time stamp 1 is 2012年11月02日 23:32:47:413:450 No_of_bits_set are 1 Time stamp 2 is 2012年11月02日 23:32:47:413:774 <<<< approx 300 Micro seconds No_of_bits_set are 1 Time stamp 3 is 2012年11月02日 23:32:47:413:809 <<<< approx 35 Micro seconds No_of_bits_set are 1 Time stamp 4 is 2012年11月02日 23:32:47:413:832 <<< approx 23 Micros !!!! :-) << similarly can be calculated for other number as well .... Enter any number 65535 Time stamp 1 is 2012年11月02日 23:33:10:851:616 No_of_bits_set are 16 Time stamp 2 is 2012年11月02日 23:33:10:851:973 No_of_bits_set are 16 Time stamp 3 is 2012年11月02日 23:33:10:852:8 No_of_bits_set are 16 Time stamp 4 is 2012年11月02日 23:33:10:852:31

Multiple declarations of global variable is valid in C


Declaring a variable multiple times globally is perfectly valid in C. This is due to the fact that variable declaration in the local function is declaration and definition, where as global variable declaration is tentative definition. That means, global variable declaration wont allocates space , until it defined or at the end the file, it allocates to zero.

Tentative Definition: when we declare the global variable, it just declares and it wont allocate space or memory to that variable, because we may declare and define the same variable in other file using extern or similar process. So to avoid these conflicts, compiler won't allocate space until all the files compiled, then allocates and initialises to zero if not initialised. And if you try to initialise while declaring the global variable more than once you will get the compilation error.

Below is the sample C Program:

#include<stdio.h>
int x;
int x; //valid
int x; //valid
int x=20; //defining here so valid
//int x=30; //invalid, redefinition
int x; //valid
int main(void)
{
printf("%d\n", x);
int x = 40;
printf("%d\n", x);
return 0;
}



Monday, November 4, 2013

C program how to find the cube of a number using recursion!!


One of my cousin asked this question. So thought of sharing this. The tricky thing here is, if we use recursion, we dont get power of 3, we will get power of 2,4,6 ... etc. To get the cube, we need to call the recursive function two times, so that we will get the number to the power of 4, then devide that result by given number, so that you will get the given number cube.

Given number cube = number to the power of 4 / number

Below is the C program for finding the cube using recursion.

#include<stdio.h>
int iterator = 2;
int givenValue=0;
int cubeOfNumber(int number)
{
 if(!iterator)
 {
 printf("cube of %d is %d\n",givenValue,number/givenValue);
 return;
 }
 else
 {
 iterator--;
 cubeOfNumber(number*number);
 }
}
int main()
{
 int n=0;
 printf("enter the number to find the cube\n");
 scanf("%d",&givenValue);
 cubeOfNumber(givenValue); 
}
OutPut:

$ ./a.out
enter the number to find the cube
3
cube of 3 is 27
$ ./a.out
enter the number to find the cube
25
cube of 25 is 15625

Sunday, November 3, 2013

How to print 1 to 100 without using loop in c!!


The basic idea is to repeat the process of printing number and not using any iteration loop. We can achieve this by using recursion. As most of you know that recursion is calling the same function repeatedly until it reaches the termination condition. We can do printing 1 to n numbers in two ways by using recursion.

  • Calling main function repeatedly
  • Calling user defined function repeatedly


Using main() function: We will maintain the global variable with initial value zero. and call the main() function in the main function, if the i value reaches 100 or required value(n), we will return. If the i value is not 100, print the i value and increment i and call main function.

#include<stdio.h>
int i=0;
int main()
{
 if(i>100)
 return 0;
 printf("%d ",i);
 i++;
 main();
}
Output:
$ ./a.out
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

Using User defined function: We will follow same logic as we did for above method, this time we will call user defined method withOutLoop instead of main function.

#include<stdio.h>
int i=0;
int withOutLoop()
{
 if(i>100)
 return 0;
 printf("%d ",i);
 i++;
 withOutLoop();
}
int main()
{
 withOutLoop();
}
OutPut:
$ ./a.out
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

Thursday, October 24, 2013

What is strdup string function in C Language?

strdup string library function is used to create the duplicate string. It will do the following three steps.

  • It creates the dynamic memory (no need to use malloc/calloc)
  • It copies the content to the newly allocated memory
  • It returns the allocated memory starting address
When we are using strdup function, we need use the free() function do deallocate memory which is allocated by strdup function, other we will get into the memory leak. Check the below sample code.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ONE_INT 1
void display()
{
 int local_a = 7;
 int *local_p = (int *)malloc(ONE_INT);
 printf("local memory location is %p\n",&local_a);
 printf("memory location using malloc is %p\n",local_p);
}
int main()
{
 char str_a[] = "Hello World";
 char *str_p = strdup(str_a);
 printf("local meory location is %p\n",str_a);
 printf("strdup memory location is %p\n",str_p);
 display();
}
OutPut:
local meory location is 0x7fff54cc0ba8
strdup memory location is 0x7fd0904000e0
local memory location is 0x7fff54cc0b7c
memory location using malloc is 0x7fd0904038a0

We can clearly observe that red colour address is from heap and blue colour address is from Stack.

Thursday, October 17, 2013

What is the difference between exit() and _exit() in C and Unix

In C programming language, exit function is used to terminate the process. Exit function will be called automatically when the program is terminates. exit() cleans up the user-mode data related to library. exit() function internally calls _exit() function which cleans up kernel related data before terminating the process.

exit() flushes the IO related buffer before exiting the process and calls the _exit() function. Where as _exit() function just terminates the process without cleaning up or flushing user data. It is not advisable to call the _exit() function in your programming until unless you are very clear. There is another function called _Exit() function which also works same as _exit() functionally. We need to use strlid.h for exit() and unistd.h for _exit() functions.

Sample code with exit function:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
 printf("Hello");
 exit(0);
}
Output:
programs$ ./a.out
Helloprograms$

Explanation:
Result we got as expected and there is no \n at the end, so on the same line prompt came.

Sample code with _exit function:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
 printf("Hello");
 _exit(0);
}
OutPut:
It prints nothing.
Explanation:
This is due to ,we called _exit() function directly, so IO related data is not flushed, so printf data is not flushed, because of this, it has printed nothing.

Sample code with _exit function with \n:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
 printf("Hello\n");
 _exit(0);
}
OutPut:
programs$ ./a.out
Hello
programs$

Explanation:
We got the output Hello, this is due to we are forcefully flushing the data using '\n'. Infact printf() function wont print or flush the data until buffer completes or end of the character is \n. printf internally maintains some buffer.

Using GDB, we can see functions which are called when the process terminates. giving below for your info for simple c program
int main()
{
 printf("Hello");
}

programs$ gdb a.out
GNU gdb 6.3.50-20050815 (Apple version gdb-1824) (Wed Feb 6 22:51:23 UTC 2013)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"...Reading symbols for shared libraries .. done
(gdb) br main
Breakpoint 1 at 0x100000f14: file _exit.c, line 5.
(gdb) r
Starting program: /Users/kh1279/Desktop/practice/Blog/programs/a.out 
Reading symbols for shared libraries +............................. done
Breakpoint 1, main () at _exit.c:5
5		printf("Hello");
(gdb) 
(gdb) n
6	}
(gdb) 
0x00007fff933ab7e1 in start ()
(gdb) 
Single stepping until exit from function start, 
which has no line number information.
0x00007fff933ab808 in dyld_stub_exit ()
(gdb) 
Single stepping until exit from function dyld_stub_exit, 
which has no line number information.
0x00007fff8b4a4f74 in exit ()
(gdb) 
Single stepping until exit from function exit, 
which has no line number information.
Hello0x00007fff8b4eb576 in dyld_stub___exit ()
(gdb) 
Single stepping until exit from function dyld_stub___exit, 
which has no line number information.
0x00007fff8efa3ae0 in _exit ()
(gdb) 
Single stepping until exit from function _exit, 
which has no line number information.
Program exited with code 0377.
(gdb) 
The program is not being run.
(gdb) 
Explanation:
you just compile your program using -g option for gcc, without this option, we cant use GDB. after compilation, launch GDB debugger using gdb with a.out or your program binary file. put a break point at main function and forward using next or n gdb command. You can find the exit and _exit functions calling in the above gdb process in red colour.

Sunday, October 13, 2013

What is the return type of the printf() function in C


printf function return type is integer. As most of us knows that, printf function is used to print content in the specified format on the standard output. It returns the no.of characters it printed on the standard out put device. i.e for hello string, printf function returns 5 as length of the string is 5 and for integer value 200, printf returns 3 as 200 contains three characters. and for float value 20.034 it returns 6 as it has 6 characters including dot. printf treats \n as a character, so if you use \n in the printf function, return value includes \n as well. sample code and syntax , see below.

Syntax for printf function in C:


int printf(const char * restrict format, ...)


Example with characters:

#include<stdio.h>
int main()
{
 int i = printf("string is %s","hello");
 int j = printf("\n%s","hello");
 printf("\ni value is %d\n",i);
 printf("j value is %d\n",j);
}
OutPut:

string is hello
hello
i value is 15
j value is 6


Example with Integers:
#include<stdio.h>
int main()
{
 int j=200;
 int k=20;
 int i = printf("%d",j);
 int l = printf("\n%d",k);
 printf("\ni value is %d\n",i);
 printf("l value is %d\n",l);
}
OutPut:

200
20
i value is 3
l value is 3


Example with Float and character:
#include#include<stdio.h>
int main()
{
 float k=20.034;
 int c='a';
 int i = printf("%d",c);
 int a = printf("%c",c);
 int l = printf("\n%f",k);
 printf("\ni value is %d\n",i);
 printf("a value is %d\n",a);
 printf("l value is %d\n",l);
}

OutPut:

97a
20.034000
i value is 2
a value is 1
l value is 10

Saturday, October 5, 2013

What is the return value of the main() function in C?

As per standard C , main() function always returns int. mostly zero if it is success and error code if it fails. some compilers accepts void as a return type for main() function. But standard compilers like gcc will give you the warning at the time of compilation saying that void is not allowed as a return type for the main() function.

#include<stdio.h>
void main()
{
 printf("testing return type for main");
}

Below is the warning message you will get when compiling using GCC for the above sample code:

$ gcc main.c
main.c: In function ‘main’:
main.c:3: warning: return type of ‘main’ is not ‘int’
Why main() returns int: In C , main() is the user entry point to execute the code, so whatever writing the code in main, it is user specified code. But internally C execute many functions before and after the main function to startup and exit the program/application. So when exiting C program, it calls exit() function and it internally calls _exit() function to exit the program. This exit process, specifies whether exit process completed successfully or any failure occurred due to some reason. If success it returns zero and if it fails it will return error code which is generally a numeric value. so logically it should return integer.

Friday, October 4, 2013

How to call function before main() function in C

Calling a user defined function before main() function: This is possible using function attributes. The standard C supports attributes syntax which is compiler dependent. C also supports type attributes, variable attributes. For more details about attributes click here.

Using function attributes, we can call the function before the main function by specifying the parameter as constructor. This will be called at startup and mostly when shared libraries are called. We can also use destructor for calling the method after main() function, which indicates the exit of the application/program.

Below is the sample code:

#include&lt;stdio.h>
void beforeMain() __attribute__((constructor));
void afterMain() __attribute__((destructor));
void beforeMain()
{
 printf("before main \n");
}
void afterMain()
{
 printf("after main \n");
}
int main()
{
 printf("In main function \n");
 printf("leaving main function \n");
}

Output: below is the result of the above program.

$ ./a.out
before main
In main function
leaving main function
after main

Explanation: This is because of function attribute constructor will be called at the time of start, before main() function and function attribute destructor will be called at the time of exit, after the main() function.


Sunday, September 29, 2013

Introduction to C programming Language

What is language: A language is a communication medium or interface between two different systems. or a language is set of rules which can be mutually understandable.

Natural Languages: The Natural languages like English, Telugu, Hindi are used to communicate between the human beings. Each natural language has set of rules called grammar.

Programming language: As language is communication medium, programming language also a communication medium/interface between machine and human being. E.g: Assembly language, C, C++, JAVA, PHP. There are two types of programming languages namely

  • Low level languages
  • High level languages

Low level languages: As machine understands only binary data like 0 or 1, so machine language is binary language. And human does not understand huge binary code, we need interface to communicate which low level language called assembly language. These are processor dependent languages. Which have limited no. of instructions like ADD, MOV, INC, JMP.
High Level languages: As humans cant remember all the assembly level instructions, so we have high level languages like JAVA, C++, PHP, Python. High level languages have the instruction similar to natural language instructions like if, while, for etc.


Natural Language Vs Programming Language: As both are languages, difference is natural languages are context sensitive and where as programming languages are context free. Context sensitive means depending on the context meaning will change. Where as for context free means, there is only one meaning, there is no context.

E.g: for Context sensitive

  • I like Cricket
  • He is playing cricket like Sachin
Here for Like , there is a separate meaning in both the sentences.


Introduction to C Language: C is a general-purpose programming language initially developed by Dennis Ritchie. C is one of the most widely used programming languages of all time. And C is used to develop applications in different domains like

  • System programs (operating systems, compilers, assemblers)
  • Embedded systems
  • Numerical computations
  • Graphical applications
  • Security applications
C language supports both low level language and high level language features. C is very efficient and power full language as it directly interacts with hardware using low level features. Because of this features, most of the applications which need efficiency and fast execution are developed in C language. Unix operating system itself developed in C Language. Below are the some of the unique features of C.


There are different types of compilers. well known compilers are given below. For more C compilers click here.

  • GCC
  • Turbo C or Borland C




Saturday, September 28, 2013

C programming language tutorials


C Programming language Basics:
  • Introduction to C Language
  • C keywords and identifiers
  • C variables and constants
  • C programming data types
  • C input/output
  • C programming operators
  • C Introduction examples
Decision and loops:
  • C programming if..else
  • C programming for loops
  • C do..while loops
  • C break and continue
  • C Switch ..case statement
  • C programming goto
  • Decision and loop examples
C programming language functions:
  • C function introduction
  • C user defined functions
  • C function types
  • C programming recursion
  • C storage class
  • C function example
Arrays and strings:
  • C arrays introduction
  • C multi-dimensional arrays
  • C arrays and functions
  • C programming strings
  • C string functions
  • C array examples
  • C string examples
C programming language pointers:
  • C pointer introduction
  • C pointers and arrays
  • C pointers and functions
  • Memory Management
  • Dynamic memory allocation
  • C pointer examples
Structure and union:
Bitwise Operators:
  • AND, OR, XOR,NOT
  • Common bitwise operations
  • Bit-fields


C programming language Miscellaneous:
  • C enumeration
  • C pre-processors
  • Precedence and associativity
  • C library functions
  • C programming examples



Thursday, August 8, 2013

reversing a given string using recursion C program!!

Below is the simple C program for reverse a given string using recursion. Check here for non-recursive ways to reverse a string.

#include<stdio.h>
#include<string.h>
void reverse(char *str2,char *str1 )
{
 if(*str1)
 {
 str2[strlen(str1) - 1] = str1[0];
 reverse(str2, str1+1);
 }
}
int main()
{
 char str1[20],str2[20];
 printf("Enter a string for str1 :");
 gets(str1);
 printf("\n Source string:%s",str1);
 memset (str2, 0, 20);
 reverse (str2, str1);
 printf(" \n Destination string:%s \n",str2);
 return 0;
}

Sample Output:
warning: this program uses gets(), which is unsafe.
Enter a string for str1 :reverse

Source string:reverse
Destination string:esrever

Let me know or comment below for any info or some bug if you find in the above code.

Sunday, July 28, 2013

Stack implementation in C

#include<stdio.h>
#define STACKSIZE 20
//stack size is 20
int stack[STACKSIZE]={0};
//top of the stack initially -1 which means empty
int tos=-1;
void push(int ele)
{
 if(tos>=STACKSIZE)
 {
 printf("err: Stack is full\n");
 }
 else
 {
 tos++;
 stack[tos] = ele; 
 }
}
int pop()
{
 if(tos==-1)
 {
 printf("err: stack is empty\n");
 }
 else
 {
 int temp = stack[tos];
 tos--;
 printf("poped element from the stack is %d\n",temp);
 return temp; 
 }
}
void display()
{
 int i;
 for(i=0;i<=tos;i++)
 printf(" %d\n",stack[i]);
 if(tos== -1)
 {
 printf("err: stack is empty\n");
 return;
 }
}
int main()
{
 int ch,ele;
 printf("enter the choice 1-push 2-pop 3-display 9-exit\n");
 scanf("%d",&ch);
 while(ch!=9)
 {
 switch(ch)
 {
 case 1: printf("Enter the ele to push\n");
 scanf("%d",&ele);
 push(ele);
 break;
 case 2: ele = pop();
 break;
 case 3: display();
 break;
 case 4:
 break;
 default:
 break;
 }
 printf("enter the choice 1-push 2-pop 3-display 9-exit\n");
 scanf("%d",&ch);
 }
}

Saturday, April 20, 2013

Simple calculator program in C!!

Recently one of my friend asked me to implement simple Application in C which reads simple calculator commands from the input file and writes the result in the output. Below is the complete description of the problem. And You can find the complete C programming language source code as well.

Simple Calculator Description:

The first line of the file contains two characters giving the initials of the user (such as GN). The rest of the file consists of a sequence of commands. Each line of the command file contains one command.

Each command starts with a character and may have zero or more operands. You may assume that the data file has no errors. The number of commands in the file is unknown. But your processing may stop as soon as the Quit command is processed. The commands are: integer add, integer subtract, integer multiply, integer divide, change to uppercase, change to lowercase, separate, print out all digits, printout the k-th digit, round real number to desired number of decimal places, divide number into two.


Calculator Commands:
-------------------------------------

+ i j [Integer Add] Add integers i and j and print out result

* i j [Integer Multiply] Multiply integers i and j and print out result

- i j [Integer Subtract ] Subtract integer j from i and print out result

/ i j [Integer Divide ] Divide integer i by j and print out result of integer division

C Ch [Character Case Change ] Change character Ch to uppercase and print it out

c Ch [Character Case Change] Change character Ch to lowercase and print it out

P i k [Print k-th Digit ] Print out the k-th digit of integer i

R x i [Round Reals ] Round double value x to i decimal places

S x [Separate ] Separate out the sign, integer part and fractional part of double value x

D i x [Partition Integer ] Given integers i and x, print out two integers j and k, where the sum of j and k equals i, and when you take x% of i and truncate it you get j

H [Help ] Print a short synopsis of all the available commands

Q [Quit ] Quit

Click here for the C source code

C source code for simple calculator!!

Below is the complete working C source code for the simple calculator. Click here for the problem description. This programs takes the input file name as a command line argument and write the result in the output.dat in the current directory.

//
// main.c
// Calculator
//
// Created by chanduthedev on 4/18/13.
//
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
void add(int first, int second,FILE * ofp)
{
 printf("%d + %d = %d\n",first,second,first+second);
 fprintf(ofp,"%d + %d = %d\n",first,second,first+second);
 
}
void multiply(int first, int second,FILE *ofp)
{
 printf("%d * %d = %d\n",first,second,first * second);
 fprintf(ofp,"%d * %d = %d\n",first,second,first * second);
}
void substract(int first, int second, FILE *ofp)
{
 
 printf("%d - %d = %d\n",first,second,first-second);
 fprintf(ofp,"%d - %d = %d\n",first,second,first-second);
}
void divide(int first,int second, FILE * ofp)
{
 
 fprintf(ofp,"%d / %d = %d\n",first,second,first/second);
 printf("%d / %d = %d\n",first,second,first/second);
}
void toUpperCase(char ch, FILE * ofp)
{
 printf("%c ==> %c\n",ch,toupper(ch));
 fprintf(ofp,"%c ==> %c\n",ch,toupper(ch));
}
void toLowerCase(char ch,FILE * ofp)
{
 printf("%c ==> %c\n",ch,tolower(ch));
 fprintf(ofp,"%c ==> %c\n",ch,tolower(ch));
}
void printKthDigit(int val, int k,FILE * ofp)
{
 int i=1;
 int temp =val;
 while(temp >0)
 {
 if(i == k)
 {
 printf("%d (digit @ %d) ==> %d\n",val,k, temp%10);
 fprintf(ofp,"%d (digit @ %d) ==> %d\n",val,k, temp%10);
 break;
 };
 i++;
 temp = temp/10;
 }
 
}
void roundDecimal(double x, int n, FILE * ofp)
{
 char temp[32]="";
 
 double rounded = round(x);
 
 sprintf(temp,"%.*lf",n,rounded);
 printf("%lf (precision=%d) => %s\n",x,n,temp);
 fprintf(ofp,"%lf (precision=%d) => %s\n",x,n,temp);
 
}
void separte(double x , FILE * ofp)
{
 char temp[32]="";
 char sign;
 int intPart;
 int fraction;
 sprintf(temp,"%lf",x);
 
 sscanf(temp,"%d.%d",&intPart,&fraction);
 
 if(intPart > 0)
 sign = '+';
 else
 {
 sign = '-';
 intPart = -1 * intPart;
 }
 printf("%lf ==> sign=%c, integer=%d,fraction=%d\n",x, sign,intPart,fraction);
 fprintf(ofp,"%lf ==> sign=%c, integer=%d,fraction=%d\n",x, sign,intPart,fraction);
}
void partitionInteger(int i, int x, FILE * ofp)
{
 int j;
 int k;
 
 j = floor(x* i/100.0);
 
 k = i-j;
 
 printf("i=%d,x=%d ==> j=%d, k=%d \n",i,x,j,k);
 fprintf(ofp,"i=%d,x=%d ==> j=%d, k=%d \n",i,x,j,k);
}
void help( FILE * ofp)
{
 printf("\n *** Help Menu! See below for Calculator Commands: ***\n");
 printf("\n + i j ---> Add integers i and j \n");
 printf("\n * i j ---> Multiply integers i and j \n");
 printf("\n + -i j ---> Subtract integer j from i \n");
 printf("\n /i j ---> Divide integer i by j \n");
 printf("\n C Ch ---> Change character Ch to uppercase \n");
 printf("\n c Ch ---> Change character Ch to lowercase \n");
 printf("\n P i k ---> Print out the k-th digit of integer i \n");
 printf("\n R x i ---> Round double value x to i decimal places \n");
 printf("\n S x ---> Separate out the sign, integer part and fractional part of double value x \n");
 printf("\n D i x ---> Given integers i and x, print out two integers j and k, where the sum of j and k equals i, and when you take x'percent' of i and truncate it you get j \n");
 printf("\n H ---> view all commands \n");
 printf("\n Q ---> Quit program\n");
 
}
int main(int argc, const char * argv[])
{
 if(argc != 2)
 {
 printf("Usage ");
 exit(0);
 }
 
 const char * inFile=argv[1];
 
 char str[64];
 int lineNum=1;
 int first,second;
 double firstDouble;
 char ch;
 char outFile[]="outData.dat";
 
 FILE * ofp = fopen(outFile,"w");
 
 FILE * fp = fopen(inFile,"r");
 while(fgets(str,64,fp) != NULL)
 {
 if(lineNum == 1)
 {
 printf("Initial %s",str);
 }
 else
 {
 char * temp = str;
 char cmd = temp[0];
 temp++; //ignore command
 temp++; //ignore space;
 
 printf("CMD=%c : ",cmd);
 if(cmd == '+')
 {
 sscanf(temp,"%d %d",&first,&second);
 add(first,second,ofp);
 }
 else if (cmd == '*')
 {
 sscanf(temp,"%d %d",&first,&second);
 multiply(first,second,ofp);
 }
 else if (cmd == '-')
 {
 sscanf(temp,"%d %d",&first,&second);
 substract(first,second,ofp);
 }
 else if (cmd == '/')
 {
 sscanf(temp,"%d %d",&first,&second);
 divide(first,second,ofp);
 }
 else if (cmd == 'C')
 {
 sscanf(temp,"%c",&ch);
 toUpperCase(ch,ofp);
 }
 else if (cmd == 'c')
 {
 sscanf(temp,"%c",&ch);
 toLowerCase(ch,ofp);
 }
 else if (cmd == 'P')
 {
 sscanf(temp,"%d %d",&first, &second);
 printKthDigit(first,second,ofp);
 }
 else if (cmd == 'R')
 {
 sscanf(temp, "%lf %d",&firstDouble,&second);
 roundDecimal(firstDouble, second,ofp);
 }
 else if (cmd == 'S')
 {
 sscanf(temp,"%lf",&firstDouble);
 separte(firstDouble,ofp);
 }
 else if (cmd == 'D')
 {
 sscanf(temp,"%d %d",&first,&second);
 partitionInteger(first,second,ofp);
 }
 else if (cmd == 'H')
 {
 help(ofp);
 }
 else if (cmd == 'Q')
 {
 break;//quits
 }
 else
 {
 printf("Function Z not implemented yet!");
 }
 }
 lineNum++;
 }
 
 fclose(fp);
 fclose(ofp);
 return 0;
}
Input file format:

KING
H
+ 2 5
- 10 5
* 8 9
/ 92 3
c A
C b
P 56234 3
R 3.64195 2
S -51.235
D 50 10

OutPut:
2 + 5 = 7
10 - 5 = 5
8 * 9 = 72
92 / 3 = 30
A ==> a
b ==> B
56234 (digit @ 3) ==> 2
3.641950 (precision=2) => 4.00
-51.235000 ==> sign=-, integer=51,fraction=235000
i=50,x=10 ==> j=5, k=45


Subscribe to: Posts (Atom)

Popular Posts

AltStyle によって変換されたページ (->オリジナル) /