Sei sulla pagina 1di 12

• Variables and Types

• Arrays
• Multidimensional Arrays
• Conditions
• Strings
• For loops
• While loops
• Functions
• Static

Introduction
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.
C is a very common language, and it is the language of many applications such as Windows, the
Python interpreter, Git, and many many more.
C is a compiled language - which means that in order to run it, the compiler (for example, GCC or
Visual Studio) must take the code that we wrote, process it, and then create an executable file. This
file can then be executed, and will do what we intended for the program to do.

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;

Notice that every line in C must end with a semicolon, so that the compiler knows that a new line
has started.
Last but not least, we will need to call the function printf to print our sentence.

Variables and Types

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.

The different types of variables define their bounds. A char can range only from -128 to 127,
whereas a long can range from -2,147,483,648 to 2,147,483,647 (long and other numeric data
types may have another range on different computers, for example - from –
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit computer).
Note that C does not have a boolean type. Usually, it is defined using the following notation:
#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 */

Arrays
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.

Multidimensional Arrays
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 −

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'}
};

the compiler would already know that there are two "dimensions" you could say, but, you need need
NEED a [ y ] value!! The compiler may be smart, but it will not know how many integers,
characters, floats, whatever you're using you have in the dimensions. Keep that in mind.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be used by specifying bracketed[] values for each row. Below is an
array with 3 rows and each row has 4 columns. To make it easier, you can forget the 3 and keep it
blank, it'll still work.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The inside braces, which indicates the wanted row, are optional. The following initialization is the
same to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example −
int val = a[2][3];

The above statement will take the 4th element from the 3rd row of the array.

Conditions

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.");
}

You can also nest if else statements if you like.


int peanuts_eaten = 22;
int peanuts_in_jar = 100;
int max_peanut_limit = 50;

if (peanuts_in_jar > 80) {


if (peanuts_eaten < max_peanut_limit) {
printf("Take as many peanuts as you want!\n");
}
} else {
if (peanuts_eaten > peanuts_in_jar) {
printf("You can't have anymore peanuts!\n");
}
else {
printf("Alright, just one more peanut.\n");
}
}

Two or more expressions can be evaluated together using logical operators to check if two
expressions evaluate to true together, or at least one of them. To check if two expressions both
evaluate to true, use the AND operator &&. To check if at least one of the expressions evaluate to
true, use the OR operator ||.
int foo = 1;
int bar = 2;
int moo = 3;

if (foo < bar && moo > bar) {


printf("foo is smaller than bar AND moo is larger than bar.");
}

if (foo < bar || moo > bar) {


printf("foo is smaller than bar OR moo is larger than bar.");
}

The NOT operator ! can also be used likewise:


int target = 9;
if (target != 10) {
printf("Target is not equal to 10");

Strings

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));

String comparison
The function strncmp compares between two strings, returning the number 0 if they are equal, or
a different number if they are different. The arguments are the two strings to be compared, and the
maximum comparison length. There is also an unsafe version of this function called strcmp, but it
is not recommended to use it. For example:
char * name = "John";

if (strncmp(name, "John", 4) == 0) {
printf("Hello, John!\n");
} else {
printf("You are not John. Go away.\n");
}

String Concatenation
The function 'strncat' appends first n characters of src string to the destination string where n is
min(n,length(src)); The arguments passed are destination string, source string, and n - maximum
number of characters to be appended. For Example:
char dest[20]="Hello";
char src[20]="World";
strncat(dest,src,3);
printf("%s\n",dest);
strncat(dest,src,20);
printf("%s\n",dest);

For loops
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);
}

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);

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++;
}

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;
}
}

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);
}

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();

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.");
}

Static vs Global?
While static variables have scope over the file containing them making them accessible only inside
a given file, global variables can be accessed outside the file too.

Potrebbero piacerti anche