Sie sind auf Seite 1von 23

Chapter 1: C Introduction

C is a general-purpose, imperative computer programming language, supporting structured


programming lexical variable scope and recursion, while a static type system prevents many
unintended operations. By design, C provides constructs that map efficiently to typical machine
instructions, and it has therefore found lasting use in applications that were previously coded in
assembly language. Such applications include operating systems, as well as various application
software for computers ranging from supercomputers to embedded systems.

C was originally developed at Bell Labs by Dennis Ritchie, between 1972 and 1973. It was created to
make utilities running on Unix. Later, it was applied to re-implementing the kernel of the Unix operating
system[6]. During the 1980s, C gradually gained popularity. Nowadays, it is one of the most widely used
programming languages, with C compilers from various vendors available for the majority of existing
computer architectures and operating systems. C has been standardized by the American National
Standards Institute (ANSI) since 1989 (see ANSI C) and subsequently by the International Organization
for Standardization (ISO).

C is an imperative procedural language. It was designed to be compiled using a relatively


straightforward compiler, to provide low-levelaccess to memory, to provide language constructs that
map efficiently to machine instructions, and to require minimal runtime support. Despite its low-level
capabilities, the language was designed to encourage cross-platform programming. A standards-
compliant C program that is written with portabilityin mind can be compiled for a wide variety of
computer platforms and operating systems with few changes to its source code; the language has
become available on various platforms, from embedded microcontrollers to supercomputers.

History

Developing C was not originally the objective of its founders. In fact, various circumstances and problems
created the ideal situation for its creation. In the 1960s, Dennis Ritchie, who was an employee of Bell Labs
(AT&T), along with some of his colleagues, had been working on developing an operating system which could
be used by many users simultaneously. This operating system was known as Multics, and it was meant to allow

1
many users to share common computing resources. Multics offered many benefits, but also had many problems.
It was a large system and it seemed – from a cost-benefit perspective – that the costs outweighed the benefits.
Gradually, Bell Labs withdrew from the project.

Evolution of C

Over time, C began to be used in personal computers for developing software applications and other purposes.

The first change (even if only a little) came when the American National Standards Institute (ANSI) formed a
committee in 1983 to standardize C. After a review of the language, they modified it a little so that it was also
compatible with other programs that preceded C. So the new ANSI standard came into being in 1989, and is
known as ANSI C or C89. The International Organization for Standardization (ISO) has also contributed to the
standardization of C.

2
Chapter 2: Data Types

In the C programming language, data types are declarations for memory locations or variables that determine
the characteristics of the data that may be stored and the methods
(operations) of processing that are permitted involving them.

The C language provides basic arithmetic types, such as integer and real number types, and syntax to build array
and compound types. Several headers in the C standard library contain definitions of support types, that have
additional properties, such as providing storage with an exact size, independent of the implementation.

Some of the data types are:

Data Types Explanation

char Smallest addressable unit of the machine


that can contain basic character set. It is
an integer type. Actual type can be either
signed or unsigned. It contains
CHAR_BIT bits.
signed char Of the same size as char , but
guaranteed to be signed.
unsigned char Of the same size as char , but
guaranteed to be unsigned.
short Short signed integer type. Capable of
short int containing at least the [−32,767,
signed short +32,767] range. Thus, it is at least 16 bits
in size.
signed short int

long Long signed integer type. Capable of


long int containing at least the
signed long [−2,147,483,647,+2,147,483,647] range.
Thus, it is at least 32 bits in size.
signed long int

int Basic signed integer type. Capable of


signed containing at least the
signed int [−32,767,+32,767] range. Thus, it is at
least 16 bits in size.

Variable

3
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.

Constant

Constants refer to fixed values that the program may not alter during its execution. These fixed values are also
called literals.

Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant,
or a string literal. There are enumeration constants as well.

Constants are treated just like regular variables except that their values cannot be modified after their definition.

Storage Classes

• A storage class defines the scope (visibility) and life-time of variables and/or functions
within a C Program. They precede the type that they modify. We have four different
storage classes in a C program −

◦ auto

◦ register

◦ static

◦ extern

Operators in C

Arithmetic Operator

+ Addition Adds values on either side of the operator. a + b = 30

4
- Subtraction Subtracts right hand operand from left hand a – b = -10
operand.

* Multiplies values on either side of the operator a * b = 200


Multiplication

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand b%a=0


and returns remainder

^ Exponent Performs exponential (power) calculation on a^b =10 to the


operators power 20

Comparator Operators

Operator Description Example

== If the values of two operands are equal, then the (a == b) is


condition becomes true. not true.

!= If values of two operands are not equal, then condition (a != b) is


becomes true. true.

> If the value of left operand is greater than the value of (a > b) is
right operand, then condition becomes true. not true.

< If the value of left operand is less than the value of (a < b) is
right operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal to (a >= b) is


the value of right operand, then condition becomes not true.
true.

<= If the value of left operand is less than or equal to the (a <= b) is
value of right operand, then condition becomes true. true.

Logical Operators
5
Operator Description Example

Logical AND If both the operands are true then condition becomes (a && b)
true. is true.

Logical OR If any of the two operands are non-zero then condition (a || b) is


becomes true. true

6
Chapter 3: Arrays

Overview

An array is a collection of a fixed number of values of a single type. For example: if you want to
store 100 integers in sequence, you can create an array for it.

For example −

int data[100];

The size and type of arrays cannot be changed after its declaration.

Arrays are of two types:


1. One-dimensional arrays
2. Multidimensional arrays

How to declare arrays

data_type array_name[array_size];

For example,

float mark[5];

Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point values.

Elements of an Array and How to access them?

You can access elements of an array by indices.

7
Suppose you declared an array mark as above. The first element is mark[0], second element is mark[1] and so
on.

Few key notes:


• Arrays have 0 as the first index not 1. In this example, mark[0]
• If the size of an array is n, to access the last element, (n-1)index is used. In this example, mark[4]
• Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d, address of
a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.

How to initialize an array?

It's possible to initialize an array during declaration.


For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int mark[] = {19, 10, 8, 17, 9};

Here,

mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17

8
mark[4] is equal to 9

How to insert and print any elements?

int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element


mark[3] = 9;

// take input from the user and insert in third element


scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element


scanf("%d", &mark[i]);

// print first element of an array


printf("%d", mark[0]);

// print ith element of an array


printf("%d", mark[i-1]);

Important thing to remember when working with C arrays

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can use the array members from testArray[0] to testArray[9].

If you try to access array elements outside of its bound, let's say testArray[12], the compiler may not show any
error. However, this may cause unexpected output (undefined behavior).

9
Chapter 4: Flow Control

In programming, decision making is used to specify the order in which statements are executed. In this tutorial,
you will learn to write if...else statements to make decisions in your program.

C if else statement

The syntax of if else statement is:

if (testExpression) {
// statement(s) inside the body of if
}
else {
// statement(s) inside the body of else
}

10
Loops

Loops are used in programming to repeat a block of code until a specific condition is met. There are three loops
in C programming:

1. for loop
2. while loop
3. do while loop

1. for loop

The syntax of for loop is:


for (initializationStatement; testExpression; updateStatement) {
// codes
}

2. While loop

The syntax of a while loop is:

while (testExpression) {
//codes
}

3. Do while loop

do{
// codes
}
while (testExpression);

Break continue

The break statement terminates the loop, whereas continue statement forces the next iteration of the loop. In this
tutorial, you will learn to use break and continue with the help of examples.

Break Statement

The break statement terminates the loop (for, while and do...while loop) immediately when it is encountered. Its
syntax is:

break;

11
Continue Statement

The continue statement skips statements after it inside the loop. Its syntax is:

continue;

C switch

The switch statement is often faster than nested if...else (not always). Also, the syntax of switch statement is
cleaner and easy to understand.

Syntax:

switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;

case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}

When a case constant is found that matches the switch expression, control of the program passes to the block of
code associated with that case.

Suppose, the value of n is equal to constant2. The compiler executes the statements after case constant2: until
break is encountered. When break statement is encountered, switch statement terminates.

12
Chapter 5: Functions
A function is a block of code that performs a specific task.
Suppose, a program related to graphics needs to create a circle and color it depending upon the radius and color
from the user. You can create two functions to solve this problem:
• create a circle function
• color function

Dividing complex problem into small components makes program easy to understand and use.

Types of function

Depending on whether a function is defined by the user or already included in C compilers, there are two types
of functions in C programming
There are two types of function in C programming:
1. Standard library functions
2. User defined functions

Standard library functions

The standard library functions are built-in functions in C programming to handle tasks such as mathematical
computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file, these functions are available for
use. For example:
The printf() is a standard library function to send formatted output to the screen (display output on the screen).
This function is defined in "stdio.h" header file.

13
There are other numerous library functions defined under "stdio.h", such as scanf(), fprintf(), getchar() etc. Once
you include "stdio.h" in your program, all these functions are available for use.

User defined functions

C allow programmers to define functions. Such functions created by the user are called user-defined functions.
You can create as many user-defined functions as you want.

How user-defined function works?

#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}

int main()
{
... .. ...
... .. ...

functionName();

... .. ...
... .. ...
}

NOTE: Function name is an identifier and should be unique.

Advantages of user-defined functions

1. The program will be easier to understand, maintain and debug.


2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can be divided among many
programmers.

14
Chapter 6: Pointers

Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and
other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes
necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address defined which can
be accessed using ampersand (&) operator, which denotes an address in memory.

What are pointers?

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.
Like any variable or constant, you must declare a pointer before using it to store any variable address.

Syntax

type *var-name;

Null Pointer

It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called
a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.

In most of the operating systems, programs are not permitted to access memory at address 0 because that
memory is reserved by the operating system. However, the memory address 0 has special significance; it signals
that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer
contains the null (zero) value, it is assumed to point to nothing.

Example code

15
#include <stdio.h>

int main () {

int var1;

char var2[10];

printf("Address of var1 variable: %x\n", &var1 );

printf("Address of var2 variable: %x\n", &var2 );

return 0;

When the above code is compiled and executed, it produces the following result −

Address of var1 variable: bff5a400

Address of var2 variable: bff5a3f6

Chapter 7: Strings

Overview

Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed by a null.

16
The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the number
of characters in the word "Hello."

Syntax:

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Following is the memory presentation of the above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C compiler automatically places
the '\0' at the end of the string when it initializes the array.

Example code 1:

#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

printf("Greeting message: %s\n", greeting );

return 0;

17
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello

Example code 2:

#include <stdio.h>

#include <string.h>

int main () {

char str1[12] = "Hello";

char str2[12] = "World";

char str3[12];

int len ;

/* copy str1 into str3 */

strcpy(str3, str1);

printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */

strcat( str1, str2);

printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */

len = strlen(str1);

printf("strlen(str1) : %d\n", len );

return 0;

When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello

strcat( str1, str2): HelloWorld

strlen(str1) : 10

18
Chapter 8: Structures

Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure
is another user defined data type available in C that allows to combine data items of different kinds.

Structures are used to represent a record. Suppose you want to keep track of your books in a library.

Defining a structure

To define a structure, you must use the struct statement. The struct statement defines a new data type, with more
than one member. The format of the struct statement is as follows −

struct [structure tag] {

member definition;

member definition;

...

member definition;

19
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f;
or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can
specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −

struct Books {

char title[50];

char author[50];

char subject[100];

int book_id;

} book;

Accessing structure members

To access any member of a structure, we use the member access operator (.). The member access operator is
coded as a period between the structure variable name and the structure member that we wish to access. You
would use the keyword struct to define variables of structure type.

Pointers to structures

You can define pointers to structures in the same way as you define pointer to any other variable −
struct Books *struct_pointer;

Now, you can store the address of a structure variable in the above defined pointer variable. To find the address
of a structure variable, place the '&'; operator before the structure's name as follows −

struct_pointer = &Book1;

To access the members of a structure using a pointer to that structure, you must use the → operator as follows −

struct_pointer->title;

20
Chapter 9: Input and Output

When we say Input, it means to feed some data into a program. An input can be given in the form of a file or
from the command line. C programming provides a set of built-in functions to read the given input and feed it to
the program as per requirement.

When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a
set of built-in functions to output the data on the computer screen as well as to save it in text or binary files.

The standard files

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file pointers are the means to access the file for reading and writing purpose. This section explains how to
read values from the screen and how to print the result on the screen.

The scanf() and printf() functions

The int scanf(const char *format, …) function reads the input from the standard input stream stdin and scans
that input according to the format provided.

The int printf(const char *format, …) function writes the output to the standard output stream stdout and
produces the output according to the format provided.

The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings,
integer, character or float respectively. There are many other formatting options available which can be used
based on requirements.

21
Example:

#include <stdio.h>

int main( ) {

char str[100];

int i;

printf( "Enter a value :");

scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, i);

return 0;

When the above code is compiled and executed, it waits for you to input some text. When you enter a text and
press enter, then program proceeds and reads the input and displays it as follows −
$./a.out

Enter a value : seven 7

You entered: seven 7

22
References
 https://www.programiz.com/c-programming/
 https://en.wikipedia.org/wiki/C_(programming_language)

23

Das könnte Ihnen auch gefallen