Free Essay

C Language

In:

Submitted By PanyamSreekanth
Words 4320
Pages 18
Handout: Problem Solving and
'C' Programming

Version: PSC/Handout/1107/1.0
Date: 16-11-07

Cognizant
500 Glen Pointe Center West
Teaneck, NJ 07666
Ph: 201-801-0233 www.cognizant.com Problem Solving and C Programming

TABLE OF CONTENTS
About this Document ....................................................................................................................6
Target Audience ...........................................................................................................................6
Objectives .....................................................................................................................................6
Pre-requisite .................................................................................................................................6
Session 2: Introduction to Problem Solving and Programming Languages ...........................7
Learning Objectives ......................................................................................................................7
Problem Solving Aspect ...............................................................................................................7
Program Development Steps .......................................................................................................8
Introduction to Programming Languages ...................................................................................14
Types and Categories of Programming Languages ...................................................................15
Program Development Environments ........................................................................................18
Summary ....................................................................................................................................19
Test your Understanding ............................................................................................................19
Session 3: Introduction to C Programming Language .............................................................21
Learning Objectives ....................................................................................................................21
Introduction to C Language ........................................................................................................21
Evolution and Characteristics of C Language ............................................................................21
Structure of a C Program ............................................................................................................23
C Compilation Model ..................................................................................................................24
C Fundamentals .........................................................................................................................25
Character Set..............................................................................................................................25
Keywords ....................................................................................................................................26
Identifiers ....................................................................................................................................26
Data Types .................................................................................................................................26
Variables .....................................................................................................................................28
Constants....................................................................................................................................29
Operators ....................................................................................................................................30
Expressions ................................................................................................................................32
Type Casting...............................................................................................................................33
Input and Output Statements......................................................................................................35
Try It Out .....................................................................................................................................39
Summary ....................................................................................................................................39
Test your Understanding ............................................................................................................39
Page 2
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Session 5: Selection and Control Structures ............................................................................41
Learning Objectives ....................................................................................................................41
Basic Programming Constructs ..................................................................................................41
Sequence....................................................................................................................................42
Selection Statements ..................................................................................................................42
‘if’ Statement ...............................................................................................................................42
Conditional / Ternary / ?: Operator .............................................................................................44
Switch Statement ........................................................................................................................45
Iteration Statements ...................................................................................................................46
‘for’ statements ...........................................................................................................................46
‘while’ statement .........................................................................................................................48
‘do - while’ statement ..................................................................................................................48
Break, Continue Statements.......................................................................................................49
Try It Out .....................................................................................................................................50
Summary ....................................................................................................................................51
Test your Understanding ............................................................................................................51
Session 7: Arrays and Strings ....................................................................................................53
Learning Objectives ....................................................................................................................53
Need for an Array .......................................................................................................................53
Memory Organization of an Array...............................................................................................53
Declaration and Initialization.......................................................................................................54
Basic Operation on Arrays..........................................................................................................55
Multi-dimensional Array ..............................................................................................................56
Strings.........................................................................................................................................58
String Functions ..........................................................................................................................59
Character Functions ...................................................................................................................61
Try It Out .....................................................................................................................................61
Summary ....................................................................................................................................63
Test your Understanding ............................................................................................................63
Session 9: Functions ...................................................................................................................65
Learning Objectives ....................................................................................................................65
Need for Functions .....................................................................................................................65
Function Prototype .....................................................................................................................66
Function Definition ......................................................................................................................67
Function Call ...............................................................................................................................69
Passing Arguments ....................................................................................................................70
Functions and Arrays ..................................................................................................................73
Page 3
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Try It Out .....................................................................................................................................75
Summary ....................................................................................................................................77
Test your Understanding ............................................................................................................77
Session 10: Functions/Structures and Unions..........................................................................79
Learning Objectives ....................................................................................................................79
Storage Classes .........................................................................................................................79
Command Line Arguments .........................................................................................................82
Introduction to Structures and Unions ........................................................................................83
Declaration and Initialization.......................................................................................................84
Structures and Arrays .................................................................................................................87
Structures and Functions ............................................................................................................88
Try It Out .....................................................................................................................................89
Summary ....................................................................................................................................90
Test your Understanding ............................................................................................................90
Session 14: Structures and Unions / Files and Preprocessor directives ...............................92
Learning Objectives ....................................................................................................................92
Unions.........................................................................................................................................92
Union of Structures .....................................................................................................................93
Enumeration ...............................................................................................................................94
Typedef Statement .....................................................................................................................95
Introduction to Files ....................................................................................................................95
File Operations ...........................................................................................................................96
Character I/O ..............................................................................................................................98
String I/O...................................................................................................................................100
Numeric I/O...............................................................................................................................100
Formatted I/O............................................................................................................................101
Block I/O ...................................................................................................................................102
Try It Out ...................................................................................................................................104
Summary ..................................................................................................................................106
Test your Understanding ..........................................................................................................106
Session 15: Files and Preprocessor directives / Pointers .....................................................108
Learning Objectives ..................................................................................................................108
Random File Operations ...........................................................................................................108
Preprocessor Directives ...........................................................................................................109
Introduction to Pointers .............................................................................................................115
Declaration and Initialization.....................................................................................................115

Page 4
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Pointer Arithmetic .....................................................................................................................116
Pointers and Arrays ..................................................................................................................117
Try It Out ...................................................................................................................................123
Summary ..................................................................................................................................125
Test your Understanding ..........................................................................................................125
Session 17: Pointers ..................................................................................................................127
Learning Objectives ..................................................................................................................127
Functions and Pointers .............................................................................................................127
Structures and Pointers ............................................................................................................129
Dynamic Memory Allocation .....................................................................................................130
Try It Out ...................................................................................................................................133
Summary ..................................................................................................................................136
Test your Understanding ..........................................................................................................136
Syntax Summary ........................................................................................................................138
References ..................................................................................................................................151
Websites ...................................................................................................................................151
Books ........................................................................................................................................151
STUDENT NOTES: ......................................................................................................................152

Page 5
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Introduction

About this Document
This document provides the following topics:
Problem solving concepts
An introduction to C programming language
Basic concepts of C programming language

Target Audience
In-Campus Trainees

Objectives
Explain the concepts of problem solving
Explain the concepts of C programming language
Write effective programs using C programming language

Pre-requisite
This module does not require any pre-requisites

Page 6
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Session 2: Introduction to Problem Solving and
Programming Languages
Learning Objectives
After completing this session, you will be able to:
Explain the Problem Solving Aspect
Identify the steps involved in program development
Know about the Programming Languages and it’s types and categories
Understand the Program Development Environments

Problem Solving Aspect
Problem solving is a creative process. It is an act of defining a problem, determining the cause of the problem, identifying, prioritizing, and selecting alternatives for a solution and implementing a solution. A problem can be solved successfully only after making an effort to understand the problem. To understand the problem, the following questions help:
What do we know about the problem?
What is the information that we have to process in order the find the solution?
What does the solution look like?
What sort of special cases exist?
How can we recognize that we have found the solution?
It is important to see if there are any similarities between the current problem and other problems that have already been solved. We have to be sure that the past experience does not hinder us in developing new methodology or technique for solving a problem. The important aspect to be considered in problem-solving is the ability to view a problem from a variety of angles.

There is no universal method for solving a given problem. Different strategies appear to be good for different problems. Some of the well known strategies are:
Divide and Conquer
Greedy Method
Dynamic Programming
Backtracking
Branch and Bound

Page 7
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Program Development Steps
The various steps involved in Program Development are: o Defining or Analyzing the problem

o

Design (Algorithm)

o

Coding

o

Documenting the program

o

Compiling and Running the Program

o

Testing and Debugging

o

Maintenance

Analyzing or Defining the Problem
The problem is defined by doing a preliminary investigation. Defining a problem helps us to understand the problem clear. It is also known as Program Analysis.
Tasks in defining a problem: o Specifying the input requirements

o

Specifying the output requirements

o

Specifying the processing requirements

Specifying the input requirements
Determine the inputs required and source of the data. The input specification is obtained by answering the following questions: o What specific values will be provided as input to the program?

o

What format will the values be?

o

For each input item, what is the valid range of values that it may assume?

o

What restrictions are placed on the use of these values?

Specifying the output requirements
Describe in detail the output that will be produced. The output specification is obtained by answering the following questions: o What values will be produced?

o

What is the format of these values?

o

What specific annotation, headings, or titles are required in the report?

o

What is the amount of output that will be produced?

Specifying the Processing Requirements
Determine the processing requirements for converting the input data to output. The processing requirement specification is obtained by answering the following questions: o What is the method (technique) required in producing the desired output?

o

What calculations are needed?

o

What are the validation checks that need to be applied to the input data?

Page 8
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Example 2.1 Find the factorial of a given number
Input: Positive valued integer number
Output: Factorial of that number
Process: Solution technique which transforms input into output. Factorial of a number can be calculated by the formula n! = 1*2*3*4….*n

Design
A design is the path from the problem to a solution in code. Program Design is both a product and a process. The process results in a theoretical framework for describing the effects and consequences of a program as they are related to its development and implementation.
A well designed program is more likely to be:
Easier to read and understand later
Less of bugs and errors
Easier to extend to add new features
Easier to program in the first place
Modular Design
Once the problem is defined clearly, several design methodologies can be applied. An important approach is Top-Down programming design. It is a structured design technique which breaks up the problem into a set of sub-problems called Modules and creates a hierarchical structure of modules. While applying top-down design to a given problem, consider the following guidelines:
A problem is divided it into smaller logical sub-problems, called Modules
Each module should be independent and should have a single task to do
Each module can have only one entry point and one exit point, so that the logic flow of the program is easy to follow
When the program is executed, it must be able to move from one module to the next in sequence, until the last module is executed
Each module should be of manageable size, in order to make the design and testing easier Top-down design has the following advantages:
Breaking up the problem into parts helps us to clarify what is to be done
At each step of refinement, the new parts become more focussed and, therefore, easier to design
Modules may be reused
Breaking the problem into parts allows more than one person to work on the solution simultaneously Page 9
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Algorithm (Developing a Solution technique)
An algorithm is a step-by-step description of the solution to a problem. It is defined as an ordered sequence of well-defined and effective operations which, when carried out for a given set of initial conditions, produce output, and terminate in a finite time. The term “ordered sequence” specifies, after the completion of each step in the algorithm, the next step must be unambiguously defined.
An algorithm must be:
Definite
Finite
Precise and Effective
Implementation independent ( only for problem not for programming languages)
Developing Algorithms
Algorithm development process is a trial-and-error process. Programmers make initial attempt to the solution and review it, to test its correctness. The errors identified leads to insertions, deletions, or modifications to the existing algorithm.

This refining continues until the programmer is satisfied that, the algorithm is essentially correct and ready to be executed. The more experience we gain in developing an algorithm, the closer our first attempt will be to a correct solution and the less revision will be required. However, a novice programmer should not view developing algorithm as a single-step operation
Example 2.2: Algorithm for finding factorial of a given number
Step 1: Start
Step 2: Initialize factorial to be 1, i to be 1
Step 3: Input a number n
Step 4: Check whether the number is 0. If so report factorial is 1 and goto step 9
Step 5: Repeat step 6 through step 7 n times
Step 6: Calculate factorial = factorial * i
Step 7: Increment i by 1
Step 8: Report the calculated factorial value
Step 9: Stop

Pseudo Code
Pseudo code is an informal high-level description of an algorithm that uses the structural conventions of programming languages, but omits language-specific syntax. It is an outline of a program written in English or the user's natural language.
Example 2.3: Pseudo Code for finding factorial of a given number
Step 1: START
Step 2: DECLARE the variables n, fact, i
Step 2: SET variable fact =1 and i =1

Page 10
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Step 3: READ the number n
Step 4: IF n = 0 then
Step 4.1: PRINT factorial = 1
Step 4.2: GOTO Step 9
Step 5: WHILE the condition i p2 p1==p2

p1+2 p1-p2 (if p1, p2 points to same array)

Illegal operations p1/p2 p1*p2

p1+p2

p1/5

Pointers and Arrays
Arrays
Array is used to store the similar data items in contiguous memory locations under single name.
Array addressing is in the form of relative addressing. Compiler treats the subscript as a relative offset from the beginning of the array. Array subscripting notation is converted to pointer notation during compilation, so writing array subscripting expressions using pointer notation can save compile time.
Pointers
Pointer addressing is in the form of absolute addressing. Exact location of the elements can be accessed directly by assigning the starting location of the array to the pointer variable. The pointer variable is incremented to find the next element.
C treats the name of the array as if it is a pointer to the first element. Thus, if v is an array, *pv is the same as v[0], *(pv+1) is the same as v[1], and so on.

Pointer pointing to an array
Initialization
To initialize a pointer variable, conventional array is declared and pointer variable can be made to point to the starting location of the array. Array elements are accessed using pointer variable.

Page 117
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

General Form: pointer_variable = &array_name [starting index];
OR
pointer_variable = array_name;
Example 15.14 int a[5] = {1,2,3, 4,5} ptr = a ;

, *ptr

, i ;

similar to ptr = &a[0];

Assume that array starts at location 1000
&a[0] = 1000

a[0] = 1

ptr + 0 = 1000

*(ptr+0)

= 1

&a[1] = 1002

a[1] = 2

ptr + 1 = 1002

*(ptr+1)

= 2

&a[2] = 1004

a[2] = 3

ptr + 2 = 1004

*(ptr+2)

= 3

&a[3] = 1006

a[3] = 4

ptr + 3 = 1006

*(ptr+3)

= 4

&a[4] = 1008

a[4] = 5

ptr + 4 = 1008

*(ptr+4)

= 5

Accessing value
Example 15.15 printf (“%d “,*(ptr+i));

displays the a[i] value

printf (“%d “,*ptr);

displays the a[0] value

printf (“%d “,*(a+i));

displays the a[i] value

Accessing address
Example 15.16 printf (“%u “, (ptr+i));

displays address of a(i)

Pointers and Multi Dimensional Arrays
As the internal representation of a multi dimensional array is also linear, a pointer variable can point to an array of any dimension. The way in which the pointer variable used, varies according to the dimension.
General Form: ptr_vble = &array_name [starting index1]…[starting indexn];
OR
ptr_vble = array_name;
Example 15.17 int a[2][2] = {1,2,3,4} ,

*ptr ;

ptr = &a[0][0] ;
Assume that the array starts at location 1000
&a[0][0] = 1000

a[0][0] = 1

ptr+0 = 1000

*(ptr+0) = 1

&a[0][1] = 1002

a[0][1] = 2

ptr+1 = 1002

*(ptr+1) = 2

&a[1][0] = 1004

a[1][0] = 3

ptr+2 = 1004

*(ptr+2) = 3

&a[1][1] = 1006

a[1][1] = 4

ptr+3 = 1006

*(ptr+3) = 4

Page 118
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

If the pointer to the array is accessed with 2 subscripts, it results in a problem.
For example,
(p+0) + 1
(p+1) + 0

if it is used to represent 0th row and 1st column if it is used to represent 1st row and 0th column

and results in p+1.

So, multi dimensional arrays can be represented by pointer in the following two ways:
Pointer to a group of arrays
Array of pointers
Pointer to a group of arrays
A two dimensional array, for example, is a collection of one dimensional array. Therefore, a twodimensional array is defined as a pointer to a group of one dimensional array and in the same way three dimensional arrays can be represented by a pointer to a group of two dimensional arrays. int a[3][2] can be represented by a pointer as follows: int (*p)[2] p is a pointer points to a set of one dimensional array, each with 2 elements.
Note: First dimension need not be specified but the second dimension has to be specified. Here, a single pointer is used and it needs to know how many columns are there in a row.
The following representations are used when a pointer is pointing to a 2D array: ptr+i is a pointer to ith row.

*(ptr+i)

refers to the entire row - actually a pointer to the first element in i th row.

(*(ptr + i) +j) is a pointer to jth element in ith row
*(*(ptr+i) + j)) refers to the content available in ith row, jth column
Accessing value
Example 15.18 printf (“%d “,*(*(ptr + i) +j);

displays the x(i,j) value

printf (“%d “,*(a[ i ] + j);

displays the x(i,j) value

printf (“%d “,*(a + i)[ j ];

displays the x(i,j) value

Example 15.19 main() { int i, j; int a[2][3]={1,2,3,4,5,6}; int *pa=&a[0][0]; for (i=0;irollnum, ptr->name, ptr->semester, ptr->avg); Self-Referential structures
A structure containing a member that is a pointer to the same structure type is called selfreferential structures. It is used to build various kinds of linked data structures.
Example 17.8 struct employee
{
char name[20]; char gender; float salary; struct employee *empptr;

Dynamic Memory Allocation
Conventional arrays are static in nature, because size has to be mentioned in the declaration statement itself and fixed block of memory is reserved during the compilation.
C supports dynamic memory allocation through the following functions: malloc(), calloc () , free()
These functions provides the ability to reserve as much memory as may required during program execution, and then release this memory when it is no longer required.
Thus, arrays can be represented in terms of pointers and an initial memory location can be allocated to pointer variable by means of this memory allocation functions. int *p; p = (int *) malloc ( 10 * sizeof(int)) ;

Page 130
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

The above program constructs will return memory block of 20 bytes, which can hold 10 integers.
The starting address is pointed by the pointer ‘p’.
A one dimensional dynamic array can be declared using pointers as follows: int *p; p = (int *) calloc (10, sizeof(int));
This will return 10 continuous memory blocks of 2 bytes each and initializes them to 0. This can be used to allocate space for arrays and structures. free(p) will release the memory pointed by a pointer variable ‘p’. free() will take a void pointer.
Example 17.9: Program for adding two matrices using array of pointers void main()
{
int *a[3] , *b[3] , *c[3]; int i,j; for(i=0 ; i link; temp-> data = n; temp-> link = p;
}
return (p);
}
void printlist ( struct node *p )
{
struct node *temp; temp = p; printf("The data values in the list are\n"); if(p!= NULL)
Page 134
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

{ do { printf("%d\t",temp->data); temp=temp->link;
} while (temp!= p);
}
else printf("The list is empty\n");
}
void main()
{
int n; int x; struct node *start = NULL ; start = insert ( start, 1 ); start = insert ( start, 2); start = insert ( start, 3 ); start = insert ( start, 4 ); printf("The created list is\n"); printlist ( start ); getchar(); }
Refer File Name: to obtain soft copy of the program code

How It Works:
Declare a structure node with data as the one of the member and the link as the other member which is a pointer to same structure which will hold the address of next node.
In the main program, declare a pointer variable start pointing to struct node and initialize to NULL.
Call a function insert() and pass the start pointer and the value 1 as argument to the function. In the insert function,as it is first time, the start pointer will be NULL, so it will allocate memory and assign the value of data as 1 and the link pointing to the same pointer p.
Then returns the pointer back.
In the main program, again insert() function is called with the returned pointer from previous call and the value as 2.
Now the start pointer is not NULL, so it goes to the else part and traverse the linked list till the last node.
Then allocate memory and assign data as 2 and link pointing to the same pointer p.
Then returns back the pointer.

Page 135
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Same is continued for next two insert function call.
Now four data’s has been inserted in to the linked list.
In the main program call the printlist() function to print all the data in the linked list.
In the printlist() function, using do while loop traverse through the linked list and print all the values.

Summary
Pointer is a variable which can hold the address of another variable.
& operator is used to refer the address of a variable and * operator is used for dereferencing the pointer.
Pointer can point to an array of any dimensions.
There are two ways to represent multi dimensional arrays by means of pointers: o Single pointer points to set of arrays o Array of pointers
Strings can easily be represented using pointer – Ragged arrays. malloc(), calloc() functions are used to allocate memory dynamically. free() function is used to de-allocate the memory.

Test your Understanding
1. State whether the following are true or false
a. Pointer variable can only contain an address
b. Address of the memory location can be assigned to ordinary variables
c. Pointer can refer to the content of the memory location by & operator
d. Size of the pointer variable is equivalent to the size of the data item it points.
2. What is the use of generic pointers?
3. What is the output of the following code? main() { int n[25]; n[0]=100; n[24]=200; printf("\n%d,%d", *n, *(n+24)+*(n+0) );
}
4. Given the following declaration: int a, *b = &a , **c = &b;
What is the output of the following statements? a=4; **c=5; b = (int *)**c;

Page 136
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

5. What is the output of the following code? main( )
{
char *str1=”abcd”; char str2[]=”abcd”; printf(“%d %d %d”, sizeof(str1),sizeof(str2), sizeof(“abcd”));
}
6. Differentiate malloc() , calloc().
Answers:
1. True, false, false, false
2. Generic pointers (void pointers) can point to data items of any type.
3. 100, 300
4. The first statement assigns 4 to a. The second statement assigns 5 to the location pointed to by the location pointed to by c. Since c points to b, this is same as assigning 5 to the location pointed to by b. Since b points to a, this statement is equivalent to assigning 5 to a. The third statement castes **c, which is value of a, into type int *, assign the value to a. The result is meaningless, because values cannot be assigned to pointers.
5. 2 5 5
6. malloc(), calloc() will both allocate the memory dynamically, but the difference is calloc() will return a contiguous memory location and initializes it to 0.

Page 137
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Syntax Summary
Program Structure/Functions type fnc(type1,: : : ) type name main() { declarations statements
}

function declarations external variable declarations main routine local variable declarations

type fnc(arg1,: : : ) { declarations statements return value;
}

function definition local variable declarations

/* */

comments

main(int argc, char *argv[])

main with args

exit(arg)

terminate execution

C Preprocessor
#include

include library file

#include "filename"

include user file

#define

name text replacement text

#define name(var)

text replacement macro
Example. #define max(A,B) ((A)>(B) ? (A) : (B))

#undef name

undefine

#

quoted string in replace

##

concatenate args and rescan

#if, #else, #elif, #endif

conditional execution

#ifdef, #ifndef

is name defined, not defined?

name defined?

defined(name)

line continuation char

\

Page 138
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Data Types/Declarations character (1 byte)

char

integer

int

float (single precision)

float

float (double precision)

double

short (16 bit integer)

short

long (32 bit integer)

long

positive and negative

signed

only positive

unsigned

pointer to int, float

*int, *float

enumeration constant

enum

constant (unchanging) value

const

declare external variable

extern

register variable

register

local to source file

static

no value

void

structure

struct

create name by data type t

typedef typename

size of an object (type is size_t)

sizeof object

size of a data type (type is size_t)

sizeof(type name)

Initialization initialize variable

type name=value

initialize array

type name[]={value1,: : : }

initialize char string

char name[]="string"

Constants long (suffix)

L or l

float (suffix)

F or f

exponential form

e

octal (prefix zero)

0

hexadecimal (prefix zero-ex)

0x or 0X

character constant (char, octal, hex)

‘a’, ‘\ooo’, ‘\xhh’

newline, cr, tab, backspace

\n, \r, \t, \b

special characters

\\, \?, \, \"

string constant (ends with \0)

"abc: : : de"

Page 139
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Problem Solving and C Programming

Pointers, Arrays & Structures declare pointer to type

type *name

declare function returning pointer to type type

*f()

declare pointer to function returning type type

(*pf)()

generic pointer type

void *

null pointer

NULL

object pointed to by pointer

*pointer

address of object name

&name

array

name[dim]

multi-dim array

name[dim1][dim2]….

Structures struct tag { declarations };

structure template declaration of members

struct tag name

create structure

name.member

member of structure from template

pointer -> member Ex. (*p).x and p->x are the same member of pointed to structure

union

single value, multiple type structure

member : b

bit field with b bits

Operators (grouped by precedence) structure member operator

name.member

structure pointer

pointer->member

increment, decrement

++, --

plus, minus, logical not, bitwise not

+, -, !, ~

indirection via pointer, address of object

*pointer, &name

cast expression to type

(type) expr

size of an object

sizeof

multiply, divide, modulus (remainder)

*, /, %

add, subtract

+, -

left, right shift [bit ops]

comparisons

>, >=,

Similar Documents

Free Essay

C++ Language

...cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain corrections and changes The C++ Language Tutorial This document and its content is copyright of cplusplus.com © cplusplus.com, 2008. All rights reserved. Any redistribution or reproduction of part or all of the content in any form is prohibited other than to print a personal copy of the entire document or download it to a local hard disk, without modifying its content in any way (including, but not limited to, this copyright notice). You may not, except with express written permission from cplusplus.com, distribute the content of this document. Nor may you transmit it or store it in any other website or other form of electronic retrieval system. 2 © cplusplus.com 2008. All rights reserved The C++ Language Tutorial Table of contents Table of contents ...............................................................................................................................3 Introduction ......................................................................................................................................5 Instructions for use ................................................................................................................................... 5 Basics of C++ .............................................................

Words: 798 - Pages: 4

Free Essay

C Language

...UNIT 1 NOTES Digital Computer A digital computer is an electronic computing machine that uses the binary digits (bits) 0 and 1 to represent all forms of information internally in digital form. Every computer has a set of instructions that define the basic functions it can perform. Sequences of these instructions. Component of Digital Computer: (1)CPU: The Central Processing Unit (CPU) or the processor is the portion of a computer system that carries out the instructions of a Computer, and is the primary element carrying out the computer's functions. This term has been in use in the computer industry at least since the early 1960s . The form, design and implementation of CPUs have changed dramatically since the earliest examples, but their fundamental operation remains much the same. (2)ALU: an arithmetic logic unit (ALU) is a Digital computer that performs arthimatic and logical operations. The ALU is a fundamental building block of the central processing unit(CPU) of a computer, and even the simplest microprocessor contain one for purposes such as maintaining timers. The processors found inside modern CPUs and graphics processing units(CPU) accommodate very powerful and very complex ALUs; a single component may contain a number of ALUs. Mathematician proposed the ALU concept in 1945, when he wrote a report on the foundations for a new computer called the EDVAC. (3)Memory: memory is an organism's ability to store, retain, and recall information. Traditional studies of memory...

Words: 2515 - Pages: 11

Free Essay

C++ Languages

...Object-Oriented Programming B.Sc. Programme in Electrical and Computer Engineering C++ Basics Roman Podraza Institute of Computer Science Warsaw University of Technology Project is co-financed by European Union within European Social Fund What Is OOP ? • Object-oriented programming (OOP) is a currently popular and powerful programming technique • Main characteristics of OOP: – Encapsulation: a form of information hiding. – Inheritance: code reusability, refinement of ideas. – Polymorphism: multiple meanings in the context of inheritance. • Origins of C++ 2 A Sample Program in C++ // The first program in C++ #include using namespace std; int main () { cout 0 ) ; else x *= 3; // quite often // a block is used // // // // // e.g. empty statement keyword (optional) statement executed if boolean expression is false 22 Instructions – Multiway if-else statement if (x > 0 && x < 10) x += 10; else if (x >= 10 && x < 20) x += 20; else if (x >= 20 && x < 30) x += 30; else if (x >= 30 && x < 40) x += 40; else x += 100; 23 Instructions if (x > 0) if (y > 2) x -= y; else x += y; if (x > 0) { if (y > 2) x -= y; } else x += y; 24 Instructions • switch statement controlling expression switch ( ch ){ case (’A’): cout name == 0) // a new string (not found in the array) { res->name = new char[strlen(p) + 1]; strcpy (res->name, p); res->val = 0; } return res->val; } 40 References int main(){ const int MAX = 256; char buf[MAX]; while (cin>>buf)...

Words: 260 - Pages: 2

Free Essay

C Sharp Language Specification

...C# Language Specification Version 4.0 Notice © 1999-2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Visual Basic, Visual C#, and Visual C++ are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries/regions. Other product and company names mentioned herein may be the trademarks of their respective owners. Table of Contents 1. Introduction 1 1.1 Hello world 1 1.2 Program structure 2 1.3 Types and variables 4 1.4 Expressions 6 1.5 Statements 8 1.6 Classes and objects 12 1.6.1 Members 12 1.6.2 Accessibility 13 1.6.3 Type parameters 13 1.6.4 Base classes 14 1.6.5 Fields 14 1.6.6 Methods 15 1.6.6.1 Parameters 15 1.6.6.2 Method body and local variables 16 1.6.6.3 Static and instance methods 17 1.6.6.4 Virtual, override, and abstract methods 18 1.6.6.5 Method overloading 20 1.6.7 Other function members 21 1.6.7.1 Constructors 22 1.6.7.2 Properties 23 1.6.7.3 Indexers 23 1.6.7.4 Events 24 1.6.7.5 Operators 24 1.6.7.6 Destructors 25 1.7 Structs 25 1.8 Arrays 26 1.9 Interfaces 27 1.10 Enums 29 1.11 Delegates 30 1.12 Attributes 31 2. Lexical structure 33 2.1 Programs 33 2.2 Grammars 33 2.2.1 Grammar notation 33 2.2.2 Lexical grammar 34 2.2.3 Syntactic grammar 34 2.3 Lexical analysis 34 2.3.1 Line terminators 35 2.3.2 Comments 35 2.3.3 White space 37 2.4 Tokens 37 2.4.1 Unicode character escape sequences 37 2.4.2 Identifiers 38 2.4.3 Keywords 39 ...

Words: 47390 - Pages: 190

Free Essay

C++Language Compasion

...++Starting Out with Programming Logic and Design, 3rd Edition By Tony Gaddis C++ Language Companion or Copyright © 2013 Pearson Education, Inc. Table of Contents Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Introduction 3 Introduction to Computers and Programming 4 Input, Processing, and Output 9 Functions 19 Decision Structures and Boolean Logic 27 Repetition Structures 41 Value-Returning Functions 49 Input Validation 59 Arrays 61 Sorting and Searching Arrays 72 Files 77 Menu-Driven Programs 86 Text Processing 89 Recursion 95 Object-Oriented Programming 97 Page 2 Introduction Welcome to the C++ Language Companion for Starting Out with Programming Logic and Design, 3rd Edition, by Tony Gaddis. You can use this guide as a reference for the C++ Programming Language as you work through the textbook. Each chapter in this guide corresponds to the same numbered chapter in the textbook. As you work through a chapter in the textbook, you can refer to the corresponding chapter in this guide to see how the chapter's topics are implemented in the C++ programming language. In this book you will also find C++ versions of many of the pseudocode programs that are presented in the textbook. Note: This booklet does not have a chapter corresponding to Chapter 15 of your textbook because C++ does not provide a GUI programming library. Page 3 Chapter 1 This chapter accompanies...

Words: 1609 - Pages: 7

Free Essay

C Language

...Teach Yourself C++ in 21 Days, Second Edition Introduction Week 1 at a Glance: Day 1 Getting Started Day 2 The Parts of a C++ Program Day 3 Variables and Constants Day 4 Expressions and Statements Day 5 Functions Day 6 Basic Classes Day 7 More Program Flow Week 1 in Review Week 2 at a Glance: Day 8 Pointers Day 9 References Day 10 Advanced Functions Day 11 Arrays Day 12 Inheritance Day 13 Polymorphism Day 14 Special Classes and Functions Week 2 in Review Week 3 at a Glance: Day 15 Advanced Inheritance Day 16 Streams Day 17 The Preprocessor Day 18 Object-Oriented Analysis and Design Day 19 Templates Day 20 Exceptions and Error Handling Day 21 Whats Next Week 3 in Review Appendixes A Operator Precedence B C++ Keywords C Binary and Hexadecimal D Answers Index Teach Yourself C++ in 21 Days, Second Edition Dedication This book is dedicated to the living memory of David Levine. Acknowledgments A second edition is a second chance to acknowledge and to thank those folks without whose support and help this book literally would have been impossible. First among them are Stacey, Robin, and Rachel Liberty. I must also thank everyone associated with my books, both at Sams and at Wrox press, for being professionals of the highest quality. The editors at Sams did a fantastic job, and I must especially acknowledge and thank Fran Hatton, Mary Ann Abramson, Greg Guntle, and Chris Denny. I have taught an online course based on this book for a couple years, and many folks there...

Words: 4907 - Pages: 20

Free Essay

C Language

...Computer Programming Language Week 11 Data Files Objectives Understand Text and Binary Files  Declaring, Opening, and Closing File Streams  Reading from and Writing to Text Files  Passing and Returning Filenames  Reading from and Writing to Binary Files (Optional)  2 Files   File: collection of data that is stored together under a common name, usually on a disk, magnetic tape, or CD-ROM Each file has a unique filename, referred to as the file’s external name  For example, prices.dat and info.txt 3 Text and Binary Files  A file can be thought as an array of bytes. Characters Displayed 768A Code page: ASCII Code Software Interpretation Binary numbers, in decimal numbers: 55 54 56 65 4 ASCII Table 5 Other Code Page* How this text file is stored in computer? Hello 您好 Encode simplified Chinese • GB2312 • GB18030 • UTF-8 6 Declaring, Opening, and Closing File Streams  To store and retrieve data outside a C program, you need two items:   A file A file stream  File stream: one-way transmission path used to connect a file stored on a physical device to a program   Input file stream: receives data from a file into a program Output file stream: sends data to a file 7 File Streams 8 Declaring a File Stream    File stream is a data structure For each file that your program uses, a file stream must be named (declared) and created (opened) Declare a file stream ...

Words: 1171 - Pages: 5

Premium Essay

Learn C Programming Language in 24 Hours

...Yourself C in 24 Hours Previous | Table of Contents | Next Hour 1 - Getting Started A journey of a thousand miles is started by taking the first step. —Chinese proverb High thoughts must have high language. —Aristophanes Welcome to Teach Yourself C in 24 Hours. In this first lesson you'll learn the following:     What C is Why you need to learn C The ANSI standard Hardware and software required in order to run the C program What Is C? C is a programming language. The C language was first developed in 1972 by Dennis Ritchie at AT&T Bell Labs. Ritchie called his newly developed language C simply because there was a B programming language already. (As a matter of fact, the B language led to the development of C.) C is a high-level programming language. In fact, C is one of the most popular general-purpose programming languages. In the computer world, the further a programming language is from the computer architecture, the higher the language's level. You can imagine that the lowest-level languages are machine languages that computers understand directly. The high-level programming languages, on the other hand, are closer to our human languages. (See Figure 1.1.) Figure 1.1. The language spectrum. High-level programming languages, including C, have the following advantages:    Readability: Programs are easy to read. Maintainability: Programs are easy to maintain. Portability: Programs are easy to port across different computer platforms. The C language's...

Words: 73255 - Pages: 294

Free Essay

Assignment and Essay.... Others)Information Technology (Programming/ Languages (Java, C++, Vb,.Net, & Etc)/Database Design/ Computer Networking/ System Analysis/ Project Management/Project Development/ It & Society/ and.

...ASSIGNMENT and ESSAY. ... others)Information Technology (Programming/ Languages (Java, C++, VB, .NET, & etc)/Database Design/ Computer Networking/ System Analysis/ Project Management/Project Development/ IT & Society/ and. - NET programmers continue to struggle with the complexities of a hybrid managed/unmanaged environment. ..... Sorry, I had to laugh at that paper! ... Java on the other hand is cross-platform, and also traditionally runs as an ... - NET programmers continue to struggle with the complexities of a hybrid managed/unmanaged environment. ..... Sorry, I had to laugh at that paper! ... Java on the other hand is cross-platform, and also traditionally runsASSIGNMENT and ESSAY. ... others)Information Technology (Programming/ Languages (Java, C++, VB, .NET, & etc)/Database Design/ Computer Networking/ System Analysis/ Project Management/Project Development/ IT & Society/ and. - NET programmers continue to struggle with the complexiASSIGNMENT and ESSAY. ... others)Information Technology (Programming/ Languages (Java, C++, VB, .NET, & etc)/Database Design/ Computer Networking/ System Analysis/ Project Management/Project Development/ IT & Society/ and. - NET programmers continue to struggle with the complexities of a hybrid managed/unmanaged environment. ..... Sorry, I had to laugh at that paper! ... Java on the other hand is cross-platform, and also traditionally runs as an ... - NET programmers continue to struggle with the complexities of a hybrid managed/unmanaged environment...

Words: 784 - Pages: 4

Free Essay

Computer Science C++

...Report Bundle C++Ox: The Dawning of a New Standard Contents C++0x: The Dawning of a New Standard It's been 10 years since the first ISO C++ standard, and 2009 will bring us the second. In this special report, DevX delves into the new features being discussed by the standards team. Learn how these new features will revolutionize the way you code. Overview: C++ Gets an Overhaul It's been 10 years since the first ISO C++ standard, and 2009 will bring us the second. Learn about the new features being added and how they will revolutionize the language. Easier C++: An Introduction to Concepts C++0x concepts bring the full power of the Generic Programming paradigm to C++, making templates more expressive, easier to write, and easier to use. Spectacularly poor template error messages are a thing of the past! Simpler Multithreading in C++0x The new standard will support multithreading, with a new thread library. Find out how this will improve porting code, and reduce the number of APIs and syntaxes you use. The State of the Language: An Interview with Bjarne Stroustrup C++ founding father assesses the language on the eve of its new standard. Timeline: C++ in Retrospect From its nascent pre-processor in 1979 to today's incredibly sophisticated language features and libraries, we've documented each step along the way. C++0x: The Dawning of a New Standard Overview: C++ Gets an Overhaul Overview: C++ Gets an Overhaul C++Ox: The Dawning...

Words: 6570 - Pages: 27

Free Essay

123456789

...document. Embedded styles affect only the tags on the page they are embedded in. ex. <style type="text/css"> p { color: #00f; } </style> * external styles External styles are styles that are written in a separate document and then attached to various Web documents. External style sheets can affect any document they are attached to. ex. <link rel="stylesheet" type="text/css" href="styles.css" /> Define JavaScript? -JavaScript is an interpreted programming or script language from Netscape. It is somewhat similar in capability to Microsoft'sVisual Basic, Sun's Tcl, the UNIX-derived Perl, and IBM'sREXX. In general, script languages are easier and faster to code in than the more structured and compiled languages such as C and C++. Script languages generally take longer to process than compiled languages, but are very useful for shorter programs. Give an example of each operator in the ff below: Arithmetic There are four main arithmetic operators in C. addition + subtraction - multiplication * division / ex: y=5; z=2; x=y+z; Logical These five...

Words: 393 - Pages: 2

Free Essay

It/218 Object Oriented Programming

...Object oriented programming refers to a method of programming in which individual objects, usually called "methods" and "functions", are created and used in junction with each other to perform a function. These objects are organized within the program through use of things called structures or classes. A class is something we use to create a blueprint of sorts for a assortment of variables and components. Similarly, a structure serves the same purpose. The only difference between a structure and a class is that a structure's members are public by default and a classes members are private by default. Another form of "blueprint" used by programmers is the data union. While a union is very primitive in comparison to a structure or class, it is a good tool to use to conserve memory in larger applications. A union uses the same memory block for multiple variables at different points. While two variables in a union cannot be accessed at the same time, a union is a good way to re-use blocks of memory that would normally be left void after a variable is finished with. Now that I have covered the basic points of classes, structures and unions, I will go into more detail of just how powerful a class or structure can be. In basic reference, a class is simply a blueprint to something we create instances of later in the program. This is a very vague statement however, because in object-oriented programming the class is the backbone of the program. It is what makes the...

Words: 813 - Pages: 4

Free Essay

Cuda Overview

...speedups in fields such as medical imaging and natural resource exploration, and creating breakthrough applications in areas such as image recognition and real-time HD video playback and encoding. CUDA enables this unprecedented performance via standard APIs such as the soon to be released OpenCL™ and DirectX® Compute, and high level programming languages such as C/C++, Fortran, Java, Python, and the Microsoft .NET Framework. The CUDA Architecture The CUDA Architecture consists of several components, in the green boxes below: 1. 2. 3. 4. Parallel compute engines inside NVIDIA GPUs OS kernel-level support for hardware initialization, configuration, etc. User-mode driver, which provides a device-level API for developers PTX instruction set architecture (ISA) for parallel computing kernels and functions Device-level APIs Language Integration Applications Using DirectX Applications Using OpenCL Applications Using the CUDA Driver API C for CUDA Compute Kernels Applications Using C, C++, Fortran, Java, Python, ... C for CUDA Compute Functions HLSL Compute Shaders OpenCL C Compute Kernels DirectX Compute OpenCL Driver C...

Words: 1261 - Pages: 6

Free Essay

Akashmsd

...Introduction to the C Programming Language Science & Technology Support High Performance Computing Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212-1163 Table of Contents • • • • • • • • • Introduction C Program Structure Variables, Expressions, & Operators Input and Output Program Looping Decision Making Statements Array Variables Strings Math Library Functions • • • • • • • • • User-defined Functions Formatted Input and Output Pointers Structures Unions File Input and Output Dynamic Memory Allocation Command Line Arguments Operator Precedence Table 2 C Programming Introduction • Why Learn C? 3 C Programming Why Learn C? • • • • • • • • • Compact, fast, and powerful “Mid-level” Language Standard for program development (wide acceptance) It is everywhere! (portable) Supports modular programming style Useful for all applications C is the native language of UNIX Easy to interface with system devices/assembly routines C is terse 4 C Programming C Program Structure • • • • • Canonical First Program Header Files Names in C Comments Symbolic Constants 5 C Programming Canonical First Program • The following program is written in the C programming language: #include main() { /* My first program */ printf("Hello World! \n"); } • • C is case sensitive. All commands in C must be lowercase. C has a free-form line structure. End of each...

Words: 4639 - Pages: 19

Premium Essay

Let Us C - Yashwant Kanetkar.Pdf

...Let Us C Fifth Edition Yashavant P. Kanetkar Dedicated to baba Who couldn’t be here to see this day... About the Author Destiny drew Yashavant Kanetkar towards computers when the IT industry was just making a beginning in India. Having completed his education from VJTI Mumbai and IIT Kanpur in Mechanical Engineering he started his training company in Nagpur. Yashavant has a passion for writing and is an author of several books in C, C++, VC++, C#, .NET, DirectX and COM programming. He is a much sought after speaker on various technology subjects and is a regular columnist for Express Computers and Developer 2.0. His current affiliations include being a Director of KICIT, a training company and DCube Software Technologies, a software development company. In recognition to his contribution Microsoft awarded him the prestigious “Best .NET Technical Contributor” award recently. He can be reached at kanetkar@kicit.com. Preface to the Fifth Edition It is mid 2004. World has left behind the DOTCOM bust, 9/11 tragedy, the economic downturn, etc. and moved on. Countless Indians have relentlessly worked for close to two decades to successfully establish “India” as a software brand. At times I take secret pleasure in seeing that a book that I have been part of, has contributed in its own little way in shaping so many budding careers that have made the “India” brand acceptable. Computing and the way people use C for doing it keeps changing as years go by. So overwhelming...

Words: 46379 - Pages: 186