Wednesday 30 January 2019

C books

#BOOKS1#
Image result for C books
An Introduction to the C Programming Language
and Software Design
 
 Download

Learn C programming language tutorialspoint

Download

Monday 28 January 2019

c examples 3

#tutorial18#
Loop examples 
// Program to find factorial of a number
// For a positive integer n, factorial = 1*2*3...n

#include <stdio.h>
int main()
{
    int number;
    long long factorial;

    printf("Enter an integer: ");
    scanf("%d",&number);

    factorial = 1;

    // loop terminates when number is less than or equal to 0
    while (number > 0)
    {
        factorial *= number;  // factorial = factorial*number;
        --number;
    }

    printf("Factorial= %lld", factorial);

    return 0;
}
 
Output

Enter an integer: 5
Factorial = 120

Sunday 27 January 2019

C examples 2

#tutorial17#

// Program to find the average of n (n < 10) numbers using arrays

#include <stdio.h>
int main()
{
     int marks[10], i, n, sum = 0, average;
     printf("Enter n: ");
     scanf("%d", &n);
     for(i=0; i<n; ++i)
     {
          printf("Enter number%d: ",i+1);
          scanf("%d", &marks[i]);
          sum += marks[i];
     }
     average = sum/n;

     printf("Average = %d", average);

     return 0;
}
 
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
 
 

Friday 25 January 2019

C Examples 1

#tutorial16#

Example 1: Program to print half pyramid using *

*
* *
* * *
* * * *
* * * * *
Source Code
#include <stdio.h>
int main()
{
    int i, j, rows;

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

    for(i=1; i<=rows; ++i)
    {
        for(j=1; j<=i; ++j)
        {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
 

Example 2: Program to print half pyramid a using numbers

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
 
Source Code
#include <stdio.h> 
int main() {  
int i, j, rows; 
printf("Enter number of rows: "); 
scanf("%d",&rows);  
for(i=1; i<=rows; ++i) {  
for(j=1; j<=i; ++j) { 
printf("%d ",j);  
} printf("\n"); 
} 
return 0; 
}
 

Friday 18 January 2019

Recursion

#tutorial15#


Recursion occurs when a function contains within it a call to itself. Recursion can result in very neat, elegant code that is intuitive to follow. It can also result in a very large amount of memory being used if the recursion gets too deep.
Common examples of where recursion is used :
  • Walking recursive data structures such as linked lists, binary trees, etc.
  • Exploring possible scenarios in games such as chess
Recursion always consists of two main parts. A terminating case that indicates when the recursion will finish and a call to itself that must make progress towards the terminating case.
For example, this function will perform multiplication by recursively adding :
#include <stdio.h>

unsigned int multiply(unsigned int x, unsigned int y)
{
    if (x == 1)
    {
        /* Terminating case */
        return y;
    }
    else if (x > 1)
    {
        /* Recursive step */
        return y + multiply(x-1, y);
    }

    /* Catch scenario when x is zero */
    return 0;
}

int main() {
    printf("3 times 5 is %d", multiply(3, 5));
    return 0;
}

Arrays and Pointers


#Tutorial14#

In a previous tutorial on Pointers, you learned that a pointer to a given data type can store the address of any variable of that particular data type. For example, in the following code, the pointer variable pc stores the address of the character variable c.
char c = 'A';
char *pc = &c;
Execute Code Here, c is a scalar variable that can store only a single value. However, you are already familiar with arrays that can hold multiple values of the same data type in a contiguously allocated memory block. So, you might wonder, can we have pointers to arrays too? Indeed, we can.
Let us start with an example code and look at its output. We will discuss its behavior subsequently.
char vowels[] = {'A', 'E', 'I', 'O', 'U'};
char *pvowels = &vowels;
int i;

// Print the addresses
for (i = 0; i < 5; i++) {
    printf("&vowels[%d]: %u, pvowels + %d: %u, vowels + %d: %u\n", i, &vowels[i], i, pvowels + i, i, vowels + i);
}

// Print the values
for (i = 0; i < 5; i++) {
    printf("vowels[%d]: %c, *(pvowels + %d): %c, *(vowels + %d): %c\n", i, vowels[i], i, *(pvowels + i), i, *(vowels + i));
}
Execute Code A typical output of the above code is shown below.
&vowels[0]: 4287605531, pvowels + 0: 4287605531, vowels + 0: 4287605531
&vowels[1]: 4287605532, pvowels + 1: 4287605532, vowels + 1: 4287605532
&vowels[2]: 4287605533, pvowels + 2: 4287605533, vowels + 2: 4287605533
&vowels[3]: 4287605534, pvowels + 3: 4287605534, vowels + 3: 4287605534
&vowels[4]: 4287605535, pvowels + 4: 4287605535, vowels + 4: 4287605535
vowels[0]: A, *(pvowels + 0): A, *(vowels + 0): A
vowels[1]: E, *(pvowels + 1): E, *(vowels + 1): E
vowels[2]: I, *(pvowels + 2): I, *(vowels + 2): I
vowels[3]: O, *(pvowels + 3): O, *(vowels + 3): O
vowels[4]: U, *(pvowels + 4): U, *(vowels + 4): U

Dynamic allocation


#tutorial13#
Dynamic allocation of memory is a very important subject in C. It allows building complex data structures such as linked lists. Allocating memory dynamically helps us to store data without initially knowing the size of the data in the time we wrote the program.
To allocate a chunk of memory dynamically, we have to have a pointer ready to store the location of the newly allocated memory. We can access memory that was allocated to us using that same pointer, and we can use that pointer to free the memory again, once we have finished using it.
Let's assume we want to dynamically allocate a person structure. The person is defined like this:
typedef struct {
    char * name;
    int age;
} person;
To allocate a new person in the myperson argument, we use the following syntax:
person * myperson = malloc(sizeof(person));
Execute Code This tells the compiler that we want to dynamically allocate just enough to hold a person struct in memory, and then return a pointer to the newly allocated data.
Note that sizeof is not an actual function, because the compiler interprets it and translates it to the actual memory size of the person struct.
To access the person's members, we can use the -> notation:
myperson->name = "John";
myperson->age = 27;
After we are done using the dynamically allocated struct, we can release it using free:
free(myperson);
Execute Code Note that the free does not delete the myperson variable itself, it simply releases the data that it points to. The myperson variable will still point to somewhere in the memory - but after calling myperson we are not allowed to access that area anymore. We must not use that pointer again until we allocate new data using it.

Function arguments by reference

#Tutorial12#


Function arguments are passed by value, which means they are copied in and out of functions. But what if we copied pointers to values instead of the values themselves? This will enable us to give functions control over variables and structures of the parent functions, and not just a copy of them.
Let's say we want to write a function which increments a number by one, called addone. This will not work:
void addone(int n) {
    n++;
}

int n;
printf("Before: %d\n", n);
addone(n);
printf("After: %d\n", n);
Execute Code However, this will work:
void addone(int * n) {
    (*n)++;
}

int n;
printf("Before: %d\n", n);
addone(&n);
printf("After: %d\n", n);
The difference is that the second version of addone receives a pointer to the variable n as an argument, and then it can manipulate it, because it knows where it is in the memory.
Notice that when calling the addone function, we must pass a reference to the variable n, and not the variable itself - this is done so that the function knows the address of the variable, and won't just receive a copy of the variable itself.

Pointers to structures

Let's say we want to create a function which moves a point forward in both x and y directions, called move. Instead of sending two pointers, we can now send only one pointer to the function of the point structure:
void move(point * p) {
    (*p).x++;
    (*p).y++;
}
Execute Code However, if we wish to dereference a structure and access one of it's internal members, we have a shorthand syntax for that, because this operation is widely used in data structures. We can rewrite this function using the following syntax:
void move(point * p) {
    p->x++;
    p->y++;
}

Wednesday 16 January 2019

Pointers


#tutorial11#

Pointers


Pointers are also variables and play a very important role in C programming language. They are used for several reasons, such as:
  • Strings
  • Dynamic memory allocation
  • Sending function arguments by reference
  • Building complicated data structures
  • Pointing to functions
  • Building special data structures (i.e. Tree, Tries, etc...)
And many more.

What is a pointer?

A pointer is essentially a simple integer variable which holds a memory address that points to a value, instead of holding the actual value itself.
The computer's memory is a sequential store of data, and a pointer points to a specific part of the memory. Our program can use pointers in such a way that the pointers point to a large amount of memory - depending on how much we decide to read from that point on.

Strings as pointers

We've already discussed strings, but now we can dive in a bit deeper and understand what strings in C really are (which are called C-Strings to differentiate them from other strings when mixed with C++)
The following line:
char * name = "John";

Dereferencing

Dereferencing is the act of referring to where the pointer points, instead of the memory address. We are already using dereferencing in arrays - but we just didn't know it yet. The brackets operator - [0] for example, accesses the first item of the array. And since arrays are actually pointers, accessing the first item in the array is the same as dereferencing a pointer. Dereferencing a pointer is done using the asterisk operator *. If we want to create an array that will point to a different variable in our stack, we can write the following code:
/* define a local variable a */
int a = 1;

/* define a pointer variable, and point it to a using the & operator */
int * pointer_to_a = &a;

printf("The value a is %d\n", a);
printf("The value of a is also %d\n", *pointer_to_a);
 

Static


#Tutorial10#

Static


static is a keyword in the C programming language. It can be used with variables and functions.

What is a static variable?

By default, variables are local to the scope in which they are defined. Variables can be declared as static to increase their scope up to file containing them. As a result, these variables can be accessed anywhere inside a file.
Consider the following scenario – we want to count the runners participating in a race:

#include<stdio.h>
int runner() {
    int count = 0;
    count++;
    return count;
}

int main()
{
    printf("%d ", runner());
    printf("%d ", runner());
    return 0;
}
 
We will see that count is not updated because it is removed from memory as soon as the function completes. If static is used, however:

#include<stdio.h>
int runner()
{
    static int count = 0;
    count++;
    return count;
}

int main()
{
    printf("%d ", runner());
    printf("%d ", runner());
    return 0;
}

What is a static function?

By default, functions are global in C. If we declare a function with static, the scope of that function is reduced to the file containing it.
The syntax looks like this:
static void fun(void) {
   printf("I am a static function.");
}

Functions

#Tutorial9#

Functions


C functions are simple, but because of how C works, the power of functions is a bit limited.
  • Functions receive either a fixed or variable amount of arguments.
  • Functions can only return one value, or return no value.
In C, arguments are copied by value to functions, which means that we cannot change the arguments to affect their value outside of the function. To do that, we must use pointers, which are taught later on.
Functions are defined using the following syntax:
int foo(int bar) {
    /* do something */
    return bar * 2;
}

int main() {
    foo(1);
}
The function foo we defined receives one argument, which is bar. The function receives an integer, multiplies it by two, and returns the result.
To execute the function foo with 1 as the argument bar, we use the following syntax:
foo(1);
In C, functions must be first defined before they are used in the code. They can be either declared first and then implemented later on using a header file or in the beginning of the C file, or they can be implemented in the order they are used (less preferable).
The correct way to use functions is as follows:
/* function declaration */
int foo(int bar);

int main() {
    /* calling foo from main */
    printf("The value of foo is %d", foo(1));
}

int foo(int bar) {
    return bar + 1;
}
We can also create functions that do not return a value by using the keyword void:
void moo() {
    /* do something and don't return a value */
}

int main() {
    moo();
}

While loops


#Tutorial8#

While loops


While loops are similar to for loops, but have less functionality. A while loop continues executing the while block as long as the condition in the while remains true. For example, the following code will execute exactly ten times:
int n = 0;
while (n < 10) {
    n++;
}
Execute Code While loops can also execute infinitely if a condition is given which always evaluates as true (non-zero):
while (1) {
   /* do something */
}

Loop directives

There are two important loop directives that are used in conjunction with all loop types in C - the break and continue directives.
The break directive halts a loop after ten loops, even though the while loop never finishes:
int n = 0;
while (1) {
    n++;
    if (n == 10) {
        break;
    }
}
Execute Code In the following code, the continue directive causes the printf command to be skipped, so that only even numbers are printed out:
int n = 0;
while (n < 10) {
    n++;

    /* check that n is odd */
    if (n % 2 == 1) {
        /* go back to the start of the while block */
        continue;
    }

    /* we reach this code only if n is even */
    printf("The number %d is even.\n", n);
}

For loops

#Tutorial7#

For loops in C are straightforward. They supply the ability to create a loop - a code block that runs multiple times. For loops require an iterator variable, usually notated as i.
For loops give the following functionality:
  • Initialize the iterator variable using an initial value
  • Check if the iterator has reached its final value
  • Increases the iterator
For example, if we wish to iterate on a block for 10 times, we write:
int i;
for (i = 0; i < 10; i++) {
    printf("%d\n", i);
}
Execute Code This block will print the numbers 0 through 9 (10 numbers in total).
For loops can iterate on array values. For example, if we would want to sum all the values of an array, we would use the iterator i as the array index:
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
int i;

for (i = 0; i < 10; i++) {
    sum += array[i];
}

/* sum now contains a[0] + a[1] + ... + a[9] */
printf("Sum of the array is %d\n", sum);

Tuesday 15 January 2019

Strings

#Tutorial6#

Defining strings

Strings in C are actually arrays of characters. Although using pointers in C is an advanced subject, fully explained later on, we will use pointers to a character array to define simple strings, in the following manner:


char * name = "John Smith";
 
This method creates a string which we can only use for reading.
If we wish to define a string which can be manipulated, we will need to define it as a local character array:
char name[] = "John Smith";
This notation is different because it allocates an array variable so we can manipulate it. The empty brackets notation [] tells the compiler to calculate the size of the array automatically. This is in fact the same as allocating it explicitly, adding one to the length of the string:
char name[] = "John Smith";
/* is the same as */
char name[11] = "John Smith";
The reason that we need to add one, although the string John Smith is exactly 10 characters long, is for the string termination: a special character (equal to 0) which indicates the end of the string. The end of the string is marked because the program does not know the length of the string - only the compiler knows it according to the code.

String formatting with printf

We can use the printf command to format a string together with other strings, in the following manner:
char * name = "John Smith";
int age = 27;

/* prints out 'John Smith is 27 years old.' */
printf("%s is %d years old.\n", name, age);
Notice that when printing strings, we must add a newline (\n) character so that our next printf statement will print in a new line.

String Length

The function 'strlen' returns the length of the string which has to be passed as an argument:
char * name = "Nikhil";
printf("%d\n",strlen(name));
 

Conditions


 #Tutorial5#

Decision Making

In life, we all have to make decisions. In order to make a decision we weigh out our options and so do our programs.
Here is the general form of the decision making structures found in C.


int target = 10;
if (target == 10) {
    printf("Target is equal to 10");
}


The if statement

The if statement allows us to check if an expression is true or false, and execute different code according to the result.
To evaluate whether two variables are equal, the == operator is used, just like in the first example.
Inequality operators can also be used to evaluate expressions. For example:


int foo = 1;
int bar = 2;

if (foo < bar) {
    printf("foo is smaller than bar.");
}

if (foo > bar) {
    printf("foo is greater than bar.");
}
 
We can use the else keyword to exectue code when our expression evaluates to false.


int foo = 1;
int bar = 2;

if (foo < bar) {
    printf("foo is smaller than bar.");
} else {
    printf("foo is greater than bar.");
}
 
Sometimes we will have more than two outcomes to choose from. In these cases, we can "chain" multiple if else statements together.

 
int foo = 1;
int bar = 2;

if (foo < bar) {
    printf("foo is smaller than bar.");
} else if (foo == bar) {
    printf("foo is equal to bar.");
} else {
    printf("foo is greater than bar.");
}





Multidimensional Arrays

#Tutorial4#

In the previous tutorials on Arrays, we covered, well, arrays and how they work. The arrays we looked at were all one-dimensional, but C can create and use multi-dimensional arrays. Here is the general form of a multidimensional array declaration:


type name[size1][size2]...[sizeN];
 
For example, here's a basic one for you to look at -


int foo[1][2][3];
 
or maybe this one -


char vowels[1][5] = {
    {'a', 'e', 'i', 'o', 'u'}
};
 

Two-dimensional Arrays

The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is pretty much a list of one-dimensional arrays. To declare a two-dimensional integer array of size [ x ][ y ], you would write something like this −
type arrayName [x][y];
 
Where type can be any C data type (int, char, long, long long, double, etc.) and arrayName
 will be a valid C identifier, or variable. A two-dimensional array can 
be considered as a table which will have [ x ] number of rows and [ y ] 
number of columns. A two-dimensional array a, which contains three rows 
and four columns can be shown and thought about like this − 
 
Table 1A 
In this sense, every element in the array a is identified by an element name in the form a[i][j], where 'a' is the name of the array, and 'i' and 'j' are the indexes that uniquely identify, or show, each element in 'a'.


And honestly, you really don't have to put in a [ x ] value really, because if you did something like this -


char vowels[][5] = {
    {'A', 'E', 'I', 'O', 'U'},
    {'a', 'e', 'i', 'o', 'u'}
};
 

Arrays

#Tutorial3#

Arrays are special variables which can hold more than one value under the same variable name, organised with an index. Arrays are defined using a very straightforward syntax:
 
/* defines an array of 10 integers */
int numbers[10];
 
Accessing a number from the array is done using the same syntax. Notice that arrays in C are zero-based, which means that if we
defined an array of size 10, then the array cells 0 through 9 (inclusive) are defined. numbers[10] is not an actual value.





int numbers[10];

/* populate the array */
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
numbers[5] = 60;
numbers[6] = 70;

/* print the 7th number from the array, which has an index of 6 */
printf("The 7th number in the array is %d", numbers[6]);
Arrays can only have one type of variable, because they are implemented as a sequence of values in the computer's memory. Because of that, accessing a specific array cell is very efficient.

Variables and Types


#Tutorial2# 

Data types

C has several types of variables, but there are a few basic types:
  • Integers - whole numbers which can be either positive or negative. Defined using char, int, short, long or long long.
  • Unsigned integers - whole numbers which can only be positive. Defined using unsigned char, unsigned int, unsigned short, unsigned long or unsigned long long.
  • Floating point numbers - real numbers (numbers with fractions). Defined using float and double.
  • Structures - will be explained later, in the Structures section



#define BOOL char
#define FALSE 0
#define TRUE 1
 
C uses arrays of characters to define strings, and will be explained in the Strings section.

Defining variables

For numbers, we will usually use the type int, which an integer in the size of a "word" the default number size of the machine which your program is compiled on. On most computers today, it is a 32-bit number, which means the number can range from -2,147,483,648 to 2,147,483,647.
To define the variables foo and bar, we need to use the following syntax:
int foo;
int bar = 1;
The variable foo can be used, but since we did not initialize it, we don't know what's in it. The variable bar contains the number 1.
Now, we can do some math. Assuming a, b, c, d, and e are variables, we can simply use plus, minus and multiplication operators in the following notation, and assign a new value to a:
int a = 0,b = 1,c = 2,d = 3, e = 4;
a = b - c + d * e;
printf("%d", a); /* will print 1-2+3*4 = 11 */

Introduction

#Tutorial1#
The C programming language is a general purpose programming language, which relates closely to the way machines work. Understanding how computer memory works is an important aspect of the C programming language. Although C can be considered as "hard to learn", C is in fact a very simple language, with very powerful capabilities.

Our first program

Every C program uses libraries, which give the ability to execute necessary functions. For example, the most basic function called printf, which prints to the screen, is defined in the stdio.h header file.
To add the ability to run the printf command to our program, we must add the following include directive to our first line of the code:


#include <stdio.h> 
 
 The second part of the code is the actual code which we are going to write. The first code which will run will always reside
in the main function. 

int main() {
  ... our code goes here
}
The int keyword indicates that the function main will return an integer - a simple number. The number which will be returned by the function indicates whether the program that we wrote worked correctly. If we want to say that our code was run successfully, we will return the number 0. A number greater than 0 will mean that the program that we wrote failed. For this tutorial, we will return 0 to indicate that our program was successful:
return 0;