An Introduction to the C Programming Language
and Software Design
Learn C programming language tutorialspoint
Download
// 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// 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
* * * * * * * * * * * * * * *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;
}
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;
}
#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;
}
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.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
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.sizeof
is not an actual function, because the compiler interprets it and translates it to the actual memory size of the person struct.->
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.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.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.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++;
}
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
is a keyword in the C programming language. It can be used with variables and functions.#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;
}
static
, the scope of that function is reduced to the file containing it.static void fun(void) {
printf("I am a static function.");
}
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. 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)./* 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();
}
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 */
}
break
and continue
directives.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);
}
i
.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).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);
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));
int target = 10;
if (target == 10) {
printf("Target is equal to 10");
}
if
statementif
statement allows us to check if an expression is true
or false
, and execute different code according to the result.==
operator is used, just like in the first 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.");
}
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 −
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'}
};
/* 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.
#Tutorial2#
char
, int
, short
, long
or long long
.unsigned char
, unsigned int
, unsigned short
, unsigned long
or unsigned long long
.float
and double
.
#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 typeint
, 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 variablesfoo
andbar
, 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 variablebar
contains the number 1.
Now, we can do some math. Assuminga
,b
,c
,d
, ande
are variables, we can simply use plus, minus and multiplication operators in the following notation, and assign a new value toa
:
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 */
printf
, which prints to the screen, is defined in the stdio.h
header file. 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 functionmain
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;