블로그 이미지
Leeway is... the freedom that someone has to take the action they want to or to change their plans.
maetel

Notice

Recent Post

Recent Comment

Recent Trackback

Archive

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
  • total
  • today
  • yesterday

Category

Steve Oualline
Practical C Programming

13. Simple Pointers


183p
Pointers are also called address variables because they contain the addresses of other variables.

184p
Pointers can be used as a quick and simple way to access arrays. (...) Pointers can be used to create new variables and complex data structures such as linked lists and trees.

185p
The operator ampersand (&) returns the address of a thing which is a pointer.
The operator asterisk (*) returns the object to which a pointer points.

Operator - Meaning
* - Dereference (given a pointer, get the thing referenced)
& - Address of (given a thing, point to it)

The operator ampersand (&) returns the address of a thing which is a pointer.
The operator asterisk (*) returns the object to which a pointer points.


int *thing_ptr; // declare a pointer to a thing
thing_ptr = &thing; // point to the thing
*thing_ptr = 5; // set "thing" to 5
// The expression &thing is a pointer to a thing. The variable thing is an object
// thing_ptr points to any integer. It may or may not point to the specific variable thing.

The & (address of operator) gets the address of an object (a pointer).
The * (dereference operator) tells C to look at the data pointed to, not hte pointer itself.

http://www.cplusplus.com/doc/tutorial/pointers.html

http://www.cprogramming.com/tutorial/lesson6.html


187p
Several pointers can point to the same thing.

188p
Pointers as Function Arguments

The only result of a function is a single return value.

http://en.wikipedia.org/wiki/Call_by_value#Call_by_value

http://www.cplusplus.com/doc/tutorial/functions2.html

NULL pointer
locale.h
http://www.cplusplus.com/reference/clibrary/clocale/

189p
const Pointers

const char *answer_ptr = "Forty-Two";

char *const name_ptr = "Test";

const char *const title_ptr = "Title";

191p
Pointers and Arrays

(reminding...) 서 교수님:
number[10] 이라고 배열 선언을 하면 컴파일러는 10개의 연속된 데이터를 위한 공간을 확보하고 그 첫번째 공간의 주소를 number 에 넣습니다. 그래서 number 는 number[0] 의 주소를 가지는 것입니다.

number[1] 은 배열에서  number[0] 다음의 값을 가지는데 그 공간의 주소값을 알고 싶으면 &number[1] 이라고 하든지 number+1  이라고 하면 됩니다.

거꾸로, number 에서 시작하여 두번째 즉 number[1] 의 값을 주소로부터 얻고 싶으면 number[1] 이라고  하든지 *(number+1) 로 하여 얻을 수 있습니다.

192p
A pointer can be used to find each element of the array.

197p
Using Pointers to Split a String

strchr()
http://www.cplusplus.com/reference/clibrary/cstring/strchr.html


201p
Pointers and Structures

Instead of having to move a lot of data around, we can declare an array of pointers and then sort the pointers.


Command-Line Arguments

main (int argc, char *argv[])
{
The parameter argc is the number of arguments on the command line (including the program name).
The array argv contains the actual arguments.

(reminding...)
터미널에서, 말씀하신대로 "./V2008122-01 input.txt"라고 치면 다음과 같이 나옵니다.
argc=2
argv[0]=./V2008122-01
argv[1]=input.txt

서 교수님:
argv[0] = 실행프로그램 이름; 1번째는 항상 실행프로그램의 패스/이름 이 들어갑니다.
이번에는 argv[1] 에 들어갈 두 번째 값을 주었기 때문에 그 값이 프린트 된 것입니다.
command-line arguments는 shell 프로그램이 fileio 함수를 호출할 때 매개변수로 주는 것이고, 좀 더 엄밀하게는 OS 가 main 함수를 호출할 때 주는 것입니다.



http://www.cplusplus.com/reference/clibrary/cstdio/fprintf.html

Example 13-12: print.c
// formats files for printing
// usage: print [options] file(s)

#include <stdio.h>
#include <stdlib.h>

int verbose = 0; // verbose mode (default = false)
char *out_file = "print.out"; //output filename
char *program_name; // name of the program for erros
int line_max = 66; // number of lines per page

void do_file(char *name)
{
    printf("Verbose %d Lines %d Input %s Output %s\n",
           verbose, line_max, name, out_file);
}

void usage (void)
{
    fprintf(stderr, "Usage is %s [options] [file-list]\n",
            program_name);
    fprintf(stderr, "Options\n");
    fprintf(stderr, "    -v    verbose\n");
    fprintf(stderr, "    -l<number> Number of line\n");
    fprintf(stderr, "    -o<name>    Set output filename\n");
    exit(8);
}

int main (int argc, char *argv[])
{
    program_name =argv[0];
   
    while ( (argc>1) && (argv[1][0] == '-') )
        // argv[1][1] is the actual option character
    {
        switch (argv[1][1]) {
            case 'v':
                verbose = 1;
                break;
               
            case 'o':
                out_file = &argv[1][2];
                break;
           
            case 'l':
                line_max = atoi(&argv[1][2]);
                break;
           
            default:
                fprintf(stderr, "Bad option %s\n", argv[1]);
                usage();
        }
       
        ++argv;
        --argc;
    }
   
    if (argc == 1) {
        do_file("printf.in");
    }
    else {
        while (argc>1)
        {
            do_file(argv[1]);
            ++argv;
            --argc;
        }
    }
   
    return(0);
}

Xcode 실행창:
Verbose 0 Lines 66 Input printf.in Output print.out

terminal:
999:~/cintro/ch13/eg12 lym$ ./ch13eg12
Verbose 0 Lines 66 Input printf.in Output print.out
999:~/cintro/ch13/eg12 lym$ ./ch13eg12 i am tired
Verbose 0 Lines 66 Input i Output print.out
Verbose 0 Lines 66 Input am Output print.out
Verbose 0 Lines 66 Input tired Output print.out
999:~/cintro/ch13/eg12 lym$ ./ch13eg12 -v -l128 -0title xfile yfile zfile
Bad option -0title
Usage is ./ch13eg12 [options] [file-list]
Options
        -v      verbose
        -l<number> Number of line
        -o<name>        Set output filename
999:~/cintro/ch13/eg12 lym$ ./ch13eg12 -v -l128 -otitle xfile yfile zfile
Verbose 1 Lines 128 Input xfile Output title
Verbose 1 Lines 128 Input yfile Output title
Verbose 1 Lines 128 Input zfile Output title


208p
A pointer does not create any new space for data, but just refers to data that is created elsewhere.


http://www.cplusplus.com/doc/tutorial/pointers.html
The identifier of an array is equivalent to the address of its first element, as a pointer is equivalent to the address of the first element that it points to, so in fact they are the same concept.

An array can be considered a constant pointer.

http://www.cprogramming.com/tutorial/lesson6.html
Arrays can act just like pointers.


'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

Similarity Transformation  (0) 2008.06.10
hw 9 - ppm 이미지 회전시키기  (0) 2008.05.30
[Steve Oualline] 12. Advanced Types  (0) 2008.05.28
data type 정리  (0) 2008.05.24
[Steve Oualline] 11. Bit Operations  (0) 2008.05.14
posted by maetel

'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

[Steve Oualline] 13. Simple Pointers  (0) 2008.06.10
hw 9 - ppm 이미지 회전시키기  (0) 2008.05.30
[Steve Oualline] 12. Advanced Types  (0) 2008.05.28
data type 정리  (0) 2008.05.24
[Steve Oualline] 11. Bit Operations  (0) 2008.05.14
posted by maetel

interpolation
http://en.wikipedia.org/wiki/Interpolation

http://mathworld.wolfram.com/Interpolation.html
The computation of points or values between ones that are known or tabulated using the surrounding points or values.


ref.
http://www.cplusplus.com/reference/clibrary/cmath/


'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

[Steve Oualline] 13. Simple Pointers  (0) 2008.06.10
Similarity Transformation  (0) 2008.06.10
[Steve Oualline] 12. Advanced Types  (0) 2008.05.28
data type 정리  (0) 2008.05.24
[Steve Oualline] 11. Bit Operations  (0) 2008.05.14
posted by maetel
Steve Oualline

12. Advanced Types


Structures
http://www.cplusplus.com/doc/tutorial/structures.html

anonymous structure


Unions

176쪽 remote tape이 뭐야?


typedef


enum type
Enumerations

http://www.cplusplus.com/doc/tutorial/other_data_types.html


Casting

http://www.cplusplus.com/doc/tutorial/typecasting.html


Bit Fields or Packed Structures


'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

Similarity Transformation  (0) 2008.06.10
hw 9 - ppm 이미지 회전시키기  (0) 2008.05.30
data type 정리  (0) 2008.05.24
[Steve Oualline] 11. Bit Operations  (0) 2008.05.14
append()  (0) 2008.05.01
posted by maetel
Variables. Data Types.
http://www.cplusplus.com/doc/tutorial/variables.html



unsigned

Finally, signed and unsigned may also be used as standalone type specifiers, meaning the same as signed int and unsigned int respectively.

'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

hw 9 - ppm 이미지 회전시키기  (0) 2008.05.30
[Steve Oualline] 12. Advanced Types  (0) 2008.05.28
[Steve Oualline] 11. Bit Operations  (0) 2008.05.14
append()  (0) 2008.05.01
[Steve Oualline] 10. C Preprocessor  (0) 2008.04.22
posted by maetel
Steve Oualline

11. Bit Operations


A bit is the smallest unit of information. Normally, it is represented by the values 1 and 0. Bit manipulations are used to control the machine at the lowest level.    (156p)

compound operators (&=, |=)
http://www.cplusplus.com/doc/tutorial/operators.html

ref.
http://en.wikipedia.org/wiki/Parity_bit

http://en.wikipedia.org/wiki/Discrete_mathematics



166p
Example 11-2
#include <stdio.h>

const unsigned int HIGH_SPEED = (1<<7);

const unsigned int DIRECT_CONNECT = (1<<8);

unsigned char flags = 0;

int main()
{
    flags |= HIGH_SPEED;
    flags |= DIRECT_CONNECT;
   
    if ((flags & HIGH_SPEED) != 0)
        printf("High speed set: flags = %d %x\n", flags, flags);
   
    if ((flags & DIRECT_CONNECT) != 0)
        printf("Direct connect set: flags = %d %x\n", flags, flags);
    return(0);
}

실행 결과:
High speed set: flags = 128 80


char인 flags와 int인 DIRECT_CONNECT를 비교하면 8bits와 32bits를 비교하는 셈이다. 이때 8bits를 늘려 32bits에 맞추어 고려하게 된다. (XCode에서 컴파일하면, 추가된 자리에 통상 (signed일 때) 1을 집어 넣고 unsigned의 경우 0을 집어 넣는다. 그래서 flags를 그냥(signed) char로 선언한 경우 다음과 같이 되어 flags & DIRECT_CONNECT 가 0이 아니게 되었던 것이다.)

High speed set: flags = -128 ffffff80
Direct connect set: flags = -128 ffffff80

한편, flags를 int로 선언하고 실행하면 결과가 다음과 같다. (signed일 때와 unsigned일 때 모두 동일한 결과)

High speed set: flags = 384 180
Direct connect set: flags = 384 180



In bitmapped graphics, each pixel on the screen is represented by a single bit in memory.     (167p)



'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

[Steve Oualline] 12. Advanced Types  (0) 2008.05.28
data type 정리  (0) 2008.05.24
append()  (0) 2008.05.01
[Steve Oualline] 10. C Preprocessor  (0) 2008.04.22
hw 6 - 9장 연습문제 3번  (0) 2008.04.17
posted by maetel

by 서 교수님


int *arr;
arr = new int[N];   //C++
arr = (int *) malloc(sizeof(int)*N);    //C

"realloc"


int *A;
int len = 3;

int *append (int *A, int lA, int lB)
{
    int *B = new int[5];
    for (i=0; i<3; i++)
    {
       B[i] = A[i];
       delete [] A;
    }
    return B;
}

A = append (A, 3, 5);






posted by maetel

preprocessor
http://www.cplusplus.com/doc/tutorial/preprocessor.html



http://en.wikipedia.org/wiki/C_preprocessor
The preprocessor handles directives for source file inclusion (#include), macro definitions (#define), and conditional inclusion (#if).

http://en.wikipedia.org/wiki/Preprocessor


constants
macros
include files


#define statement

A preprocessor directive terminates at the end-of-line.
A line may be continued by putting a backslash (\) at the end.
(142쪽)

It is common programming practice to use all uppercase letters for macro names. (142쪽)

http://en.wikipedia.org/wiki/Bourne_shell

http://en.wikipedia.org/wiki/ALGOL_68


144쪽
예제 4: first.c
터미널에서 "cc -E main.cpp"라고 치니... @_@
999:~/cintro/ch10/eg4 lym$ cc -E main.cpp
# 1 "main.cpp"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "main.cpp"
# 1 "/usr/include/stdio.h" 1 3 4
# 64 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/_types.h" 1 3 4
# 27 "/usr/include/_types.h" 3 4
# 1 "/usr/include/sys/_types.h" 1 3 4
# 26 "/usr/include/sys/_types.h" 3 4
# 1 "/usr/include/sys/cdefs.h" 1 3 4
# 27 "/usr/include/sys/_types.h" 2 3 4
# 1 "/usr/include/machine/_types.h" 1 3 4
# 26 "/usr/include/machine/_types.h" 3 4
# 1 "/usr/include/ppc/_types.h" 1 3 4
# 31 "/usr/include/ppc/_types.h" 3 4
typedef signed char __int8_t;



typedef unsigned char __uint8_t;
typedef short __int16_t;
typedef unsigned short __uint16_t;
typedef int __int32_t;
typedef unsigned int __uint32_t;
typedef long long __int64_t;
typedef unsigned long long __uint64_t;

typedef long __darwin_intptr_t;
typedef unsigned int __darwin_natural_t;
# 64 "/usr/include/ppc/_types.h" 3 4
typedef int __darwin_ct_rune_t;





typedef union {
 char __mbstate8[128];
 long long _mbstateL;
} __mbstate_t;

typedef __mbstate_t __darwin_mbstate_t;


typedef int __darwin_ptrdiff_t;





typedef long unsigned int __darwin_size_t;





typedef __builtin_va_list __darwin_va_list;





typedef int __darwin_wchar_t;




typedef __darwin_wchar_t __darwin_rune_t;


typedef int __darwin_wint_t;




typedef unsigned long __darwin_clock_t;
typedef __uint32_t __darwin_socklen_t;
typedef long __darwin_ssize_t;
typedef long __darwin_time_t;
# 27 "/usr/include/machine/_types.h" 2 3 4
# 28 "/usr/include/sys/_types.h" 2 3 4



struct mcontext;
struct mcontext64;
# 60 "/usr/include/sys/_types.h" 3 4
struct __darwin_pthread_handler_rec
{
 void (*__routine)(void *);
 void *__arg;
 struct __darwin_pthread_handler_rec *__next;
};
struct _opaque_pthread_attr_t { long __sig; char __opaque[36]; };
struct _opaque_pthread_cond_t { long __sig; char __opaque[24]; };
struct _opaque_pthread_condattr_t { long __sig; char __opaque[4]; };
struct _opaque_pthread_mutex_t { long __sig; char __opaque[40]; };
struct _opaque_pthread_mutexattr_t { long __sig; char __opaque[8]; };
struct _opaque_pthread_once_t { long __sig; char __opaque[4]; };
struct _opaque_pthread_rwlock_t { long __sig; char __opaque[124]; };
struct _opaque_pthread_rwlockattr_t { long __sig; char __opaque[12]; };
struct _opaque_pthread_t { long __sig; struct __darwin_pthread_handler_rec *__cleanup_stack; char __opaque[596]; };
# 96 "/usr/include/sys/_types.h" 3 4
typedef __int64_t __darwin_blkcnt_t;
typedef __int32_t __darwin_blksize_t;
typedef __int32_t __darwin_dev_t;
typedef unsigned int __darwin_fsblkcnt_t;
typedef unsigned int __darwin_fsfilcnt_t;
typedef __uint32_t __darwin_gid_t;
typedef __uint32_t __darwin_id_t;
typedef __uint32_t __darwin_ino_t;
typedef __darwin_natural_t __darwin_mach_port_name_t;
typedef __darwin_mach_port_name_t __darwin_mach_port_t;

typedef struct mcontext *__darwin_mcontext_t;
typedef struct mcontext64 *__darwin_mcontext64_t;



typedef __uint16_t __darwin_mode_t;
typedef __int64_t __darwin_off_t;
typedef __int32_t __darwin_pid_t;
typedef struct _opaque_pthread_attr_t
   __darwin_pthread_attr_t;
typedef struct _opaque_pthread_cond_t
   __darwin_pthread_cond_t;
typedef struct _opaque_pthread_condattr_t
   __darwin_pthread_condattr_t;
typedef unsigned long __darwin_pthread_key_t;
typedef struct _opaque_pthread_mutex_t
   __darwin_pthread_mutex_t;
typedef struct _opaque_pthread_mutexattr_t
   __darwin_pthread_mutexattr_t;
typedef struct _opaque_pthread_once_t
   __darwin_pthread_once_t;
typedef struct _opaque_pthread_rwlock_t
   __darwin_pthread_rwlock_t;
typedef struct _opaque_pthread_rwlockattr_t
   __darwin_pthread_rwlockattr_t;
typedef struct _opaque_pthread_t
   *__darwin_pthread_t;
typedef __uint32_t __darwin_sigset_t;
typedef __int32_t __darwin_suseconds_t;
typedef __uint32_t __darwin_uid_t;
typedef __uint32_t __darwin_useconds_t;
typedef unsigned char __darwin_uuid_t[16];



struct sigaltstack



{
 void *ss_sp;
 __darwin_size_t ss_size;
 int ss_flags;
};

typedef struct sigaltstack __darwin_stack_t;






struct ucontext



{
 int uc_onstack;
 __darwin_sigset_t uc_sigmask;
 __darwin_stack_t uc_stack;

 struct ucontext *uc_link;



 __darwin_size_t uc_mcsize;
 __darwin_mcontext_t uc_mcontext;
};

typedef struct ucontext __darwin_ucontext_t;





struct ucontext64 {
 int uc_onstack;
 __darwin_sigset_t uc_sigmask;
 __darwin_stack_t uc_stack;
 struct ucontext64 *uc_link;
 __darwin_size_t uc_mcsize;
 __darwin_mcontext64_t uc_mcontext64;
};
typedef struct ucontext64 __darwin_ucontext64_t;
# 28 "/usr/include/_types.h" 2 3 4

typedef int __darwin_nl_item;
typedef int __darwin_wctrans_t;



typedef unsigned long __darwin_wctype_t;
# 65 "/usr/include/stdio.h" 2 3 4






typedef __darwin_va_list va_list;




typedef __darwin_size_t size_t;







typedef __darwin_off_t fpos_t;
# 98 "/usr/include/stdio.h" 3 4
struct __sbuf {
 unsigned char *_base;
 int _size;
};


struct __sFILEX;
# 132 "/usr/include/stdio.h" 3 4
typedef struct __sFILE {
 unsigned char *_p;
 int _r;
 int _w;
 short _flags;
 short _file;
 struct __sbuf _bf;
 int _lbfsize;


 void *_cookie;
 int (*_close)(void *);
 int (*_read) (void *, char *, int);
 fpos_t (*_seek) (void *, fpos_t, int);
 int (*_write)(void *, const char *, int);


 struct __sbuf _ub;
 struct __sFILEX *_extra;
 int _ur;


 unsigned char _ubuf[3];
 unsigned char _nbuf[1];


 struct __sbuf _lb;


 int _blksize;
 fpos_t _offset;
} FILE;

extern "C" {





extern FILE __sF[];

}
# 248 "/usr/include/stdio.h" 3 4
extern "C" {
void clearerr(FILE *);
int fclose(FILE *);
int feof(FILE *);
int ferror(FILE *);
int fflush(FILE *);
int fgetc(FILE *);
int fgetpos(FILE * , fpos_t *);
char *fgets(char * , int, FILE *);
FILE *fopen(const char * , const char * );
int fprintf(FILE * , const char * , ...) __asm("_" "fprintf" "$LDBLStub");
int fputc(int, FILE *);
int fputs(const char * , FILE * );
size_t fread(void * , size_t, size_t, FILE * );
FILE *freopen(const char * , const char * ,
     FILE * ) ;
int fscanf(FILE * , const char * , ...) __asm("_" "fscanf" "$LDBLStub");
int fseek(FILE *, long, int);
int fsetpos(FILE *, const fpos_t *);
long ftell(FILE *);
size_t fwrite(const void * , size_t, size_t, FILE * ) ;
int getc(FILE *);
int getchar(void);
char *gets(char *);

extern const int sys_nerr;
extern const char *const sys_errlist[];

void perror(const char *);
int printf(const char * , ...) __asm("_" "printf" "$LDBLStub");
int putc(int, FILE *);
int putchar(int);
int puts(const char *);
int remove(const char *);
int rename (const char *, const char *);
void rewind(FILE *);
int scanf(const char * , ...) __asm("_" "scanf" "$LDBLStub");
void setbuf(FILE * , char * );
int setvbuf(FILE * , char * , int, size_t);
int sprintf(char * , const char * , ...) __asm("_" "sprintf" "$LDBLStub");
int sscanf(const char * , const char * , ...) __asm("_" "sscanf" "$LDBLStub");
FILE *tmpfile(void);
char *tmpnam(char *);
int ungetc(int, FILE *);
int vfprintf(FILE * , const char * , va_list) __asm("_" "vfprintf" "$LDBLStub");
int vprintf(const char * , va_list) __asm("_" "vprintf" "$LDBLStub");
int vsprintf(char * , const char * , va_list) __asm("_" "vsprintf" "$LDBLStub");

int asprintf(char **, const char *, ...) __asm("_" "asprintf" "$LDBLStub");
int vasprintf(char **, const char *, va_list) __asm("_" "vasprintf" "$LDBLStub");

}
# 308 "/usr/include/stdio.h" 3 4
extern "C" {
char *ctermid(char *);

char *ctermid_r(char *);

FILE *fdopen(int, const char *);

char *fgetln(FILE *, size_t *);

int fileno(FILE *);
void flockfile(FILE *);

const char
 *fmtcheck(const char *, const char *);
int fpurge(FILE *);

int fseeko(FILE *, fpos_t, int);
fpos_t ftello(FILE *);
int ftrylockfile(FILE *);
void funlockfile(FILE *);
int getc_unlocked(FILE *);
int getchar_unlocked(void);

int getw(FILE *);

int pclose(FILE *);
FILE *popen(const char *, const char *);
int putc_unlocked(int, FILE *);
int putchar_unlocked(int);

int putw(int, FILE *);
void setbuffer(FILE *, char *, int);
int setlinebuf(FILE *);

int snprintf(char * , size_t, const char * , ...) __asm("_" "snprintf" "$LDBLStub");
char *tempnam(const char *, const char *);
int vfscanf(FILE * , const char * , va_list) __asm("_" "vfscanf" "$LDBLStub");
int vscanf(const char * , va_list) __asm("_" "vscanf" "$LDBLStub");
int vsnprintf(char * , size_t, const char * , va_list) __asm("_" "vsnprintf" "$LDBLStub");
int vsscanf(const char * , const char * , va_list) __asm("_" "vsscanf" "$LDBLStub");

FILE *zopen(const char *, const char *, int);

}





extern "C" {
FILE *funopen(const void *,
  int (*)(void *, char *, int),
  int (*)(void *, const char *, int),
  fpos_t (*)(void *, fpos_t, int),
  int (*)(void *));
}
# 372 "/usr/include/stdio.h" 3 4
extern "C" {
int __srget(FILE *);
int __svfscanf(FILE *, const char *, va_list) __asm("_" "__svfscanf" "$LDBLStub");
int __swbuf(int, FILE *);
}







static inline int __sputc(int _c, FILE *_p) {
 if (--_p->_w >= 0 || (_p->_w >= _p->_lbfsize && (char)_c != '\n'))
  return (*_p->_p++ = _c);
 else
  return (__swbuf(_c, _p));
}
# 2 "main.cpp" 2





int main() {
 printf("The square of all the parts is %d\n",
     7 + 5 * 7 + 5);
 return(0);
}


예제5: max.c
int main()
{
 int counter;

 for (counter = =10; counter > 0; --counter)
  printf("Hi there\n");

 return(0);
}


예제6: size.c
int main()
{
 int size;

 size = 10; -2;;
 printf("Size is %d\n", size);
 return(0);
}


예제7: die.c
int main()
{

 int value;

 value = 1;
 if (value < 0)
  fprintf((&__sF[2]), "Fatal Error:Abort\n");exit(8);;

 printf("We did not die\n");
 return (0);
}



#define vs. const

const
http://www.cprogramming.com/tutorial/const_correctness.html
The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).


Conditional Compilation

http://cplusplus.com/doc/tutorial/preprocessor.html

#ifdef
allows a section of a program to be compiled only if the macro that is specified as the parameter has been defined, no matter which its value is.

#endif
the whole structure of #if, #elif and #else chained directives ends with #endif.

#undef

#ifndef
#ifndef symbol is true if the symbol is not defined.


#else

http://en.wikibooks.org/wiki/C_Programming/Preprocessor


include Files

Files that are included in other programs are called header files.
The angle brackets (<>) indicate that the file is a standard header file. (On UNIX, these files are located in /usr/include.)

Standard include files define data structures and macros used by library routines. (eg. printf is a library routine that prints data on the standard output. The FILE structure used by printf and its related routines is defined in stdio.h.)

cstdio (stdio.h)
C library to perform Input/Output operations
http://cplusplus.com/reference/clibrary/cstdio/
This library uses what are called streams to operate with physical devices such as keyboards, printers, terminals or with any other type of files supported by the system. Streams are an abstraction to interact with these in an uniform way; All streams have similar properties independently of the individual characteristics of the physical media they are associated with.

Streams are handled in the cstdio library as pointers to FILE objects. A pointer to a FILE object uniquely identifies a stream, and is used as a parameter in the operations involving that stream.

There also exist three standard streams: stdin, stdout and stderr, which are automatically created and opened for all programs using the library.


Local include files are particulary useful for storing constants and data structures when a program spans several files. (149쪽) Local include files may be specified by using double quotes (" ") around the file name. The specification can be a simple file, a relative path, or an absolute path.


그니까 148쪽 symbol은 뭐고 149쪽 union이 뭐냐고???






posted by maetel

아우~ 진짜 어려워서 죽는 줄 알았네.
난 recursive function 아직 소화를 못 했다.
보고 이해하는 건 되는데 직접 만드는 건 무지 어렵다.
적어도 수십 개 만들어 봐야 이해할 수 있을 것 같다.
이 정도로 어렵게 느껴지는 건 C를 배운 이후 처음인 것 같다.

그동안 함수를 만들어 보지 않았던 것도 약점이 되었다.
함수를 만들려다 보니 변수명 앞에 * 붙이는 것에 대해 좀더 분명한 이해가 필요하다는 것을 깨달았다.

공부해야 할 것:
1) 함수 만들기 (만드는 버릇 들이기)
2) * (변수명) 의 활용에 대한 이해
3) recursive function 만들기 - 다양한 예제 풀어 보기



ref.
http://www.cprogramming.com/tutorial/c/lesson16.html

http://en.wikipedia.org/wiki/Recursion_%28computer_science%29

static variables
http://en.wikipedia.org/wiki/Static_variable#Static_Variables_as_Class_Variables


http://annwm.lbl.gov/~leggett/vars.html (informed by noah)


'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

append()  (0) 2008.05.01
[Steve Oualline] 10. C Preprocessor  (0) 2008.04.22
[Steve Oualline] 9. Variable Scope and Functions  (0) 2008.04.16
to calculate the exponent of a power number  (0) 2008.04.16
week 6 review  (0) 2008.04.16
posted by maetel
Steve Oualline


Scope and Class

The scope of a variable is the area of the program in which the variable is valid.

A block is a section of code enclosed in curly braces.

The declaration of a local variable takes precedence over the global declaration inside the small block in which the local variable is declared.   (127쪽)

The class of a variable may be either permanent or temporary.
Global variables are always permanent. They are created and initialized before the program starts and remain until it terminates.    (129쪽)

Temporary variables are allocated from a section of memory called the stack at the beginning of the block. The space used by the temporary variables is returned to the stack at the end of the block. Each time the block is entered, the temporary variables are initialized.   (129쪽)

Temporary variables are sometimes refered to as automatic variables because the space for them is allocated automatically.   (130쪽)


stack
webopedia:
In programming, a special type of data structure in which items are removed in the reverse order from that in which they are added, so the most recently added item is the first one removed. This is also called last-in, first-out (LIFO).
Adding an item to a stack is called pushing. Removing an item from a stack is called popping.

cf.
http://cplusplus.com/reference/stl/stack/
Cprogramming.com: The stack data structure

의문: memory는 CPU 밖에, register는 CPU 안에,  stack은 어디에? memory에?
그럼 stack은 memory인가?
memory에서 stack인 부분과 stack이 아닌 부분을 컴퓨터가 어떻게 구분짓나?
global variables는 프로그램이 끝날 때까지 memory에서 각각 하나의 주소값을 유지하나?

http://en.wikipedia.org/wiki/Stack_%28data_structure%29
a stack is an abstract data type and data structure based on the principle of Last In First Out (LIFO).

A typical stack is an area of computer memory with a fixed origin and a variable size. Initially the size of the stack is zero. A stack pointer, usually in the form of a hardware register, points to the most recently referenced location on the stack; when the stack has a size of zero, the stack pointer points to the origin of the stack.

The two operations applicable to all stacks are:

  • a push operation, in which a data item is placed at the location pointed to by the stack pointer, and the address in the stack pointer is adjusted by the size of the data item;
  • a pop or pull operation: a data item at the current location pointed to by the stack pointer is removed, and the stack pointer is adjusted by the size of the data item.


There are many variations on the basic principle of stack operations. Every stack has a fixed location in memory at which it begins. As data items are added to the stack, the stack pointer is displaced to indicate the current extent of the stack, which expands away from the origin (either up or down, depending on the specific implementation).

A stack is usually represented in computers by a block of memory cells, with the "bottom" at a fixed location, and the stack pointer holding the address of the current "top" cell in the stack. The top and bottom terminology are used irrespective of whether the stack actually grows towards lower memory addresses or towards higher memory addresses.


Many CPUs have registers that can be used as stack pointers.

In application programs written in a high level language, a stack can be implemented efficiently using either arrays or linked lists.


The size of the stack depends on the system and compiler you are using. On many UNIX systems, the program is automatically allocated the largest possible stack.   (129쪽)

cp. register
http://en.wikipedia.org/wiki/Processor_register

의문:
register에도 주소가 있을까?
register는 memory의 주소와 그 주소에 들어가는 데이터를 가지고 있는 것인가? (그렇다면 '&변수명'과 관계가 있는가?)
register가 stack에도 마찬가지로 작용하나?
만약에 그렇다면, stack에서 memory의 주소에 들어가는 데이터가 자꾸 변할 때마다 register 역시 그 정보를 동시에 알고 있다는 뜻인가? 그렇다면, 어떻게 아는 것인가? 그러니까 stack과 register는 같이 움직이나?


cf. static
It indicates that a variable is local to the current file.    (129쪽)


Functions

Functions allow us to group commonly used  code into a compact until that can be used repeatedly.   (130쪽)

Function: Name, Description, Parameters, Returns, (file formats, references, or notes)

C uses a form of parameter passing called "Call by value".   (131쪽)



function prototype

ref.   http://www.cprogramming.com/tutorial/lesson4.html
Just like a blueprint, the prototype tells the compiler what the function will return, what the function will be called, as well as what arguments the function can be passed. When I say that the function returns a value, I mean that the function can be used in the same manner as a variable would be.


void


Structured Programming

Structured programming techniques are ways of dividing up or structuring a program into small, well-defined functions.   (135쪽)

top-down programming
bottom-up programming


Recursion

Recurion occurs when a fuction calls itself directly or indirectly.    (136쪽)

1. It must have an ending point.
2. It must make the problem simpler.




posted by maetel

음냐리~ 공부하려고 한 거 아닌데... 계산기 찾는 것보다 코딩하는 게 더 간편하게 느껴져서. 쿄쿄.

//exponentiation for a number

#include <iostream>

char line[100];    // input data
int number;    // a number converted from input
int exponent = 0;   
int base = 2;

int main (int argc, char * const argv[]) {
    // to get a number from a user
    printf("Enter a number    :    ");
    fgets(line, sizeof(line), stdin);
   
    // to convert input data to number
    number = atoi(line);
   
    // to calculate its exponent on the base
    int i;
    for (i=0; number>1; i++)
    {
        number /= base;
        exponent = i+1;
    }
    printf("base %d to the %d-th power\n", base, exponent);
       
    return 0;
}



실행창:
Enter a number    :    65536
base 2 to the 16-th power


업그레이드 버전:
//exponentiation for a number

#include <iostream>

char line[100];    // input data
int number;    // a number converted from input
int exponent = 0; // exponent number to be calculated   
int base = 2; // base to power

int main (int argc, char * const argv[]) {
    while(1)
    {
        // to get a number from a user
        printf("Enter a number    :    ");
        fgets(line, sizeof(line), stdin);
       
        if (line[0]==10)    // no input but enter
            break;    // exit
        else
        {
        // to convert input data to number
            number = atoi(line);
           
            // to calculate its exponent on the base
            int i;
            int flag = 0; // indicator
            int origin = number; //to reserve the input number
            for (i=0; number>=base; i++)
            {
                int remainder = number % base;
                if (remainder != 0) //not power based on base number
                {   
                    printf("%d does not have %d-based power.\n", origin, base);
                    flag = 1; //error to calculate exponentiation
                    break;
                }
                else
                {   
                    number /= base;               
                    exponent = i+1;
                }
            }
            if (flag==1) //error
                continue;
            else if(flag==0)
                printf("base %d to the %d-th power\n", base, exponent);
        }
    }
        return 0;
}


실행창:
Enter a number    :    65536
base 2 to the 16-th power
Enter a number    :    2
base 2 to the 1-th power
Enter a number    :    3
3 does not have 2-based power.
Enter a number    :    256
base 2 to the 8-th power
Enter a number    :    255
255 does not have 2-based power.
Enter a number    :   

expon has exited with status 0.

아 놔~ 나 숙제 안 하고 뭐하고 있는 거지? 열도 안 떨어지는구만. ㅜㅜ

posted by maetel
PGM image file format

http://netpbm.sourceforge.net/

PGM
= Portable Gray Map
Jef Poskanzer @ ttp://netpbm.sourceforge.net/doc/pgm.html

http://en.wikipedia.org/wiki/Portable_Gray_Map
The portable graymap file format (PGM) provides very basic functionality and serve as a least-common-denominator for converting pixmap, graymap, or bitmap files between different platforms.

Webopedia: Graphics File Formats Reference
Portable Greymap (.pgm)
Files are created by Jef Poskanzer's PBMPlus Portable Bitmap Utilities. The portable graymap format is a lowest common denominator grayscale file format.




libnetpbm, C subroutine library
Libnetpbm Directory (the reference information for a particular function)


delimiter
webopedia: A punctuation character or group of characters that separates two names or two pieces of data, or marks the beginning or end of a programming construct. Delimiters are used in almost every computer application. For example, in specifying DOS pathnames, the backslash (\) is the delimiter that separates directories and filenames. Other common delimiters include the comma (,), semicolon (;), quotes ("), and braces ({}).
empas: 구분 문자: 임의의 기호로 이루어지는 열을 구성 요소로 구분 짓기 위한 문자. 일반적으로 구성 요소는 영문자나 정수와 같이 뜻을 갖는 경우가 많으며, 구분 문자는 동일 또는 다른 뜻을 갖는 구성 요소의 배열로부터 각각의 구성 요소를 분리하는 데 쓰인다. 포트란의 COMMON문에서 예를 들면, COMMON/ CB₁/A,B(10), C/CB₂/M, N에서는 기호 ‘/’, ‘,’가 구분 문자이다.

padding
webopedia: Filling in unused space
empas: 채우기: 고정된 길이의 블록 또는 레코드의 사용하지 않는 기억 장소를 특정 정보, 즉 공백 등의 문자로 채우는 기법.



whitespace
webopedia:
Refers to all characters that appear as blanks on a display screen or printer. This includes the space character, the tab character, and sometimes other special characters that do not have a visual form (for example, the bell character and null character).

http://en.wikipedia.org/wiki/Whitespace_%28computer_science%29
whitespace is any single character or series of characters that represents horizontal or vertical space in typography.

LF = Line Feed
http://webopedia.com/TERM/L/line_feed.html
Often abbreviated LF, a line feed is a code that moves the cursor on a display screen down one line. In the ASCII character set, a line feed has a decimal value of 10.
On printers, a line feed advances the paper one line. Some printers have a button labeled LF that executes a line feed when pressed. (Note, however, that the printer must be in off-line mode to execute a line feed.)

raster
http://webopedia.com/TERM/r/raster.html
The rectangular area of a display screen actually being used to display images. The raster is slightly smaller than the physical dimensions of the display screen. Also, the raster varies for different resolutions. For example, VGA resolution of 640x480 on a 15-inch monitor produces one raster, whereas SVGA resolution of 1,024x768 produces a slightly different raster. Most monitors are autosizing, meaning that they automatically use the optimal raster depending on the monitor's size and the video adapter's resolution. In addition, most monitors have controls that allow you move the raster, resize it, and even to rotate it.


cf.
webopedia: The science of color



FILE* fopen()
파일을 여는 함수

FILE* fclose()
파일을 닫는 함수

int fscanf()
포맷에 따라 읽는 함수

int fprintf()
포맷에 따라 쓰는 함수

char* fgets()
'\n'을 기준으로 스트링을 읽어 들이는 함수

int fputs()
스트링을 출력하는 함수

size_t fread()
블럭 단위로 읽어 들이는 함수

size_t fwrite()
블럭 단위로 파일에 쓰는 함수


size_t
Unsigned integral type

size_t
corresponds to the integral data type returned by the language operator sizeof and is defined in the <cstddef> header file (among others) as an unsigned integral type.
It expresses a size or count in bytes.



posted by maetel

for statement

to execute a block of  code for a specified number of times

for (initial-statement; condition; iteration-statement)
    body-statement;

equivalent to:
initial-statement;
while (condition) {
    body-statement;
    iteration-statement;
}


control variable
wikipedia: In programming, a control variable is a program variable that is used to regulate the flow of control of the program. For example, a loop control variable is used to regulate the number of times the body of a program loop is executed; it is incremented (or decremented when counting down) each time the loop body is executed.


switch statement

case label
default label

ref.    http://cplusplus.com/doc/tutorial/control.html
Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions.

Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they are not valid C++ constants.

If you need to check ranges or values that are not constants, use a concatenation of if and else if statements.

ref.   http://www.cprogramming.com/reference/switch.html
The braces are always needed following the switch statement. No braces are needed following any case. If the variable is equal to one of the values following a case, then the code following the case is executed. Execution will "fall through" from one case statement to the next, executing all code following the case statement, including code following other case statements and the default statement. The prevent falling through, include break;at the end of any code block. The default case will execute in the case that no other case is true.

ref.   http://www.cprogramming.com/tutorial/lesson5.html
Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char).

An important thing to note about the switch statement is that the case values may only be constant integral expressions.

ref.    http://en.wikipedia.org/wiki/Switch_statement
Its purpose is to allow the value of a variable or expression to control the flow of program execution.

cf. the switch statement in Java
A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).

cf. switch() in Processing
Program controls jumps to the case with the same value as the expression. All remaining statements in the switch are executed unless redirected by a break. Only primitive datatypes which can convert to an integer (byte, char, and int) may be used as the expression parameter. The default is optional.

A break statement inside a switch tells the computer to continue execution after the switch. If a break statement is not there, execution will continue with the next statement.    (121쪽)



switch, break, and continue


'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

to calculate the exponent of a power number  (0) 2008.04.16
week 6 review  (0) 2008.04.16
[Steve Oualline] 7. Programming Process  (0) 2008.04.05
week 4 review  (0) 2008.03.27
[Steve Ouallline] 6. Decision and Control Statements  (0) 2008.03.25
posted by maetel

setting up

unix 명령어
rm - 파일 지우기
mkdir - 디렉토리(폴더) 만들기
rmdir - 디렉토리(폴더) 지우기


module

Code design should include major algorithms, module definitions, file formats, and data structures.   (96쪽)

The code would be broken up into modules.    (98쪽)

그니까 대체 모듈이 뭐냐고~ 예전부터 애매모호하다.
In software, a module is a part of a program. Programs are composed of one or more independently developed modules that are not combined until the program is linked. A single module can contain one or several routines.

link
In programming, the term link refers to execution of a linker.

사용자 삽입 이미지

linker
Also called link editor and binder, a linker is a program that combines object modules to form an executable program. Many programming languages allow you to write different pieces of code, called modules, separately. This simplifies the programming task because you can break a large program into small, more manageable pieces. Eventually, though, you need to put all the modules together. This is the job of the linker.
In addition to combining modules, a linker also replaces symbolic addresses with real addresses. Therefore, you may need to link a program even if it contains only one module.


register (98쪽)

동아프라임:【컴퓨터】 레지스터 《CPU가 적은 양의 데이터나 처리하는 동안의 중간 결과를 일시적으로 저장하기 위해 사용하는 고속의 기억회로》
webopedia: A, special, high-speed storage area within the CPU. All data must be represented in a register before it can be processed. For example, if two numbers are to be multiplied, both numbers must be in registers, and the result is also placed in a register. (The register can contain the address of a memory location where data is stored rather than the actual data itself.)
The number of registers that a CPU has and the size of each (number of bits) help determine the power and speed of a CPU. For example a 32-bit CPU is one in which each register is 32 bits wide. Therefore, each CPU instruction can manipulate 32 bits of data.
Usually, the movement of data in and out of registers is completely transparent to users, and even to programmers. Only assembly language programs can manipulate registers. In high-level languages, the compiler is responsible for translating high-level operations into low-level operations that access registers.

사용자 삽입 이미지

메모리는 CPU 밖에 있고 레지스터는 CPU 안에 있는 것인가 보다.


Good communication is the key to good programming, and the more you can show someone the better.   (100쪽)


compilation

unix 명령어 - make
make uses the modification dates of the files to determine whether or not a compile is necessary. Compilation creates an object file. (The modification date of the object file is later than the modification date of its source. If the source was modified after the object, make recompiles the object.)   (103-104쪽)


Testing

One of the advantages of making a small working prototype is that we can isolate errors early.    (104쪽)


Debugging

Run the program and keep putting in printf statements until you isolate the area in the program that contains the mistake.

Maintenance

Revisions



rand()
Generate random number

random.c   http://fxr.watson.org/fxr/source/libkern/random.c


'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

week 6 review  (0) 2008.04.16
[Steve Oualline] 8. More Control Statements  (0) 2008.04.06
week 4 review  (0) 2008.03.27
[Steve Ouallline] 6. Decision and Control Statements  (0) 2008.03.25
week 3 review  (0) 2008.03.22
posted by maetel


strcmp
Compare two strings
Returns an integral value indicating the relationship between the strings:
A zero value indicates that both strings are equal.
A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.


printf format tags
%[flags][width][.precision][length]specifier



atoi
Convert string to integer
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.



StudentRecord record[NStudent];

StudentRecord *record;
StudentRecord *record_c;

record = new StudentRecord[NStudent];

// C++ version of allocating a memory block

record_c = (StudentRecord *) malloc (sizeof(StudentRecord)*NStudent);
// C version of allocating a memory block
// void * malloc ( size_t size );



malloc
Allocate memory block

ref.   Dynamic Memory Allocation: new and delete (C++)



"NUL indicates end-of-string." (교재 65쪽)


memcpy
서 교수님:
두 개의 struct type 데이터에 대해서, A = B;라고 하여 B를 A에 assign 하는 경우 대부분은 성립합니다. 그러나, struct 내부에서 배열을 가지고 있는 경우에는 그렇지 않습니다. 그래서 memcpy() 라는 함수를 사용하여 메모리를 블럭 단위로 카피하는 방법이 있습니다. 이는 음악 CD나 DVD 의 바이너리 카피를 만드는 것과 같은 이치입니다.




posted by maetel
Steve Oualline
Practical C Prgoramming
6. Decision and Control Statements


calculations, expressions, decision and control statements

control flow
linear programs
branching statements (cause one section of code to be executed or not executed, depending on a conditional clause)
looping statements (are used to repeat a section of code a number of times or until some condition occurs)


if Statement


if (condition)
    statement;

relational operator

"According to the C syntax rules, the else goes with the nearest if."


KISS principle (Keep It Simple, Stupid)
: We shoud write code as cleary and simply as possible.

"By adding an extra set of braces, we improve readability, understanding, and clarity."



strcmp
Compare two strings
: The function compare two strings, and then returns zero if they are equal or nonzero if they are different.
: This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminanting null-character is reached.
: Returns an integral value indicating the relationship between the strings: A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.


Looping statements
while statement

while (condition)
    statement;

The program will repeatedly execute the statement inside the while until the condition becomes false (0).

the Fibonacci numbers    (피보나치 수, 한글 위키백과)


break statement
Loops can be exited at any point through the use of a break statement.


continue statement

"Programs should be clear and simple and should not hide anything."




'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

[Steve Oualline] 7. Programming Process  (0) 2008.04.05
week 4 review  (0) 2008.03.27
week 3 review  (0) 2008.03.22
[Steve Oualline] 5. Arrays, Qualifiers, and Reading Numbers  (0) 2008.03.16
hw2  (0) 2008.03.15
posted by maetel


Read a file and see the ascii code.
ref. http://www.asciitable.com/

cstdio (stdio.h)
C library to perform Input/Output operations

FILE
Object containing information to control a stream

fgetc

Get character from stream

feof
Check End-of-File indicator


(char)

fopen

fclose

EOF (End-Of-File)
the value returned by several <cstdio> functions to indicate failure, either because the End-of-File has been reached in a reading operation or because an error happened.



Usage of memcpy function in <string.h>
void * memcpy (void * destination, const void * source, size_t num);
struct
    ref. Cprogramming.com Tutorial: Structures


size_t
Unsigned integral type
: the integral data type returned by the language operator sizeof and is defined in the <cstddef> header file (among others) as an unsigned integral type
: It expresses a size or count in bytes.

strcpy


memcpy
Copy block of memory


sizeof



Xcode 실행 결과:
Student: Hong Gil-Dong A: 38 W: 72.0
Student: Hong Gil-Dong A: 38 W: 72.0
\277\377\3660\217\341SH\277\377\366\200\277\377\367�ď\344<\\277\377\366\240���P�����\377\377\217\345&(��������\277\377\366\300�����0\360\220\325ܿ\377\367�\277\377\367�\214\217\341SH\277\377\366\360����\217\341Vp\217\345\305h�\340���P���\217\340V \277\377\366\360\277\377\367�\217\340Vt\217\345�\277\377\367���q
\331��q
\331H���\247!\340�����������\217\345\305h\217\345\305h�\340���P���\217\340\271\364\277\377\367P���P\217ຼ\217\340\250\360\277\377\367PD��"�\340��q
\331H�����\340\227!\340\227!\340���\247!\340���\277\377\370����\217\345\305h�\340��q
\331]\277\377\370�\217\340\333\277\377\370�$��"\217\340\334ܧ\230\200�����0��\217\345\305h��B��"\217\342Nd\217\3406\200����\247\230�\200�\204�\204rs/l��q
\331��q
\331\372-2/build/Deb��������������������\227!\340\227!\340\277\377\370\260\240�\234\247!\340�������\277\377\370�\217\345?����/����\277\377\370\270��\306T��\277\377\370\200�\240\217\345\305h\217\341\374\277\377\370\200"�(\217\341Ts3-2.ob�\247\230�\340\217\340\217<\277\377\370\220D��"�\340\220︿\377\370\240���P\220�L\217\345\305h\277\377\370\260\277\377\371��\303\357����������\260h\217\345\305h��\260h\277\377\370\320��\306T��\364\217\341\374\277\377\370\360\240�\324܏\341
\214\220\324\314������\2520\277\377\372\344\277\377\371X\277\377\372\350\217\3451��\340\217\3401�\277\377\371 �6\350\217\345/\220���\217\345/\220����\340\217\340/\220\277\377\3710�\340\217\34004\217\345V\220����\240���\217\340V\220\277\377\371P����\217\340WH������������\277\377\372\344\277\377\372\360\277\377\372\350����\277\377\372\344\277\377\372\360\277\377\371\200\240�\333H�6\350\220\333H\277\377\371\200����\220�L\277\377\372\360\277\377\372\350���\277\377\372\360��.\344\277\377\371\340����\217\341V\330�6\350�������\277\377\372\344\277\377\372\360\277\377\372\350�\214�6\350\220\333H\277\377\371\340\220\351\220ۤ��\2520�7\330����6\320�������\220�\360��������������������������������\277\377\372\344\277\377\372\360\277\377\372\350���\277\377\372\360��.\344\277\377\372@\277\377\372\350��/��\251\376\376\376\377\200\200\200\200�����������q\376\376\377���\217\340r\244��������\217\340s��������StudentRecord=136
double=8, float=4, int=4, char=1

shell 실행 결과:
Student: Hong Gil-Dong A: 38 W: 72.0
Student: Hong Gil-Dong A: 38 W: 72.0
#[p#####C<##SH###H##~0##~0##############^$###0#######0##^$#####^###H##C<##SH###H###\##~0#L##########################^$####0p##^L##V#######WH#########h###T##########################0p######h0####0(####0##V####@####d###h##~0##~0##~0##~0###0$"#########p###0#####0p###h0####0(#####0
                                       x(܏########"######h##
T#####SH##########SH#######X)@##<\#########h####0 ###P)##SH####M#0####@0p###h########(##T###r###/###/#############0##04000pM#l#######0p##
###V###########h##r##h#######x#L##:p#####V#0p##V####0###r##h###P##,h#ď##h###`##########`######h###pп######h##V##!D#######h###p#########h### D#######h##r#-X#######q#####r###sStudentRecord=136
double=8, float=4, int=4, char=1



An example of how to use struct in C++ programming
algorithm


struct

FileIn.is_open

FileIn.getline
http://cplusplus.com/reference/iostream/fstream/

FileIn.close

strcpy

sscanf


console:
------------------------------------------------------
 1  Name:   Peter Pan           Age:  7 W: 23.8
 2  Name: Nine-tails Fox        Age: 999        W: 50.0
 3  Name:  Genius Babo  Age: 31 W: 80.8
 4  Name: Sleepless Turandot            Age: 21 W: 48.0
 5  Name: Choon-Hyang Sung      Age: 16 W: 42.0



'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

week 4 review  (0) 2008.03.27
[Steve Ouallline] 6. Decision and Control Statements  (0) 2008.03.25
[Steve Oualline] 5. Arrays, Qualifiers, and Reading Numbers  (0) 2008.03.16
hw2  (0) 2008.03.15
week 2 review  (0) 2008.03.15
posted by maetel
Steve Oualline
Practical C Programming

5. Arrays, Qualifiers, and Reading Numbers


An array is a set of consecutive memory locations used to store data. Each item in the array is called an element. The number of elements in an array is called the dimension of the array.
To reference an element of an array, you use a number called the index -- the number inside the square brackets.



Strings are sequences of characters. Strings are just character arrays with a few restrictions.

\0


strcpy(string1, string2)
Copy string

variable-length strings


strcat(string1, string2)
Concatenate strings
: to add a space


strlen(string)
Get string length


strcmp(string1, string2)
Compare two strings


fgets
Get string from stream
fgets (name, sizeof (name), stdin);
cf. Chapter 14. File Input/Output


sizeof (name)

stdin
standard input stream


'\n'
newline

'\0'
end-of-line



Multidimensional Arrays

type variable[size1][size2];


printf

scanf
Read formatted data from stdin

fgets

sscanf
Read formatted data from string
: string scanf


C lets you give detailed information about how the hardware is to be used.    - 75p

Types of Integers
%hd
signed short int

%d
signed int

%ld
signed long int

%hu
unsigned short int

%u
unsigned int

%lu
unsigned long int


Types of Floats
%f
float (printf only)

%lf
double (scanf only)

%Lf
long doubel (not available on all compilers)



Side Effects
A side effect is an operation that is performed in addition to the main operation executed by the statement.




'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

[Steve Ouallline] 6. Decision and Control Statements  (0) 2008.03.25
week 3 review  (0) 2008.03.22
hw2  (0) 2008.03.15
week 2 review  (0) 2008.03.15
[Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
posted by maetel

hw2

1. 주어진 데이터를 내림차순으로 정렬하는 프로그램을 작성하시오.
2. 주어진 데이터를 오름차순으로 정렬하는 프로그램을 작성하시오.

붉은 줄을 빼 먹는 바람에... ㅡㅜ 일일이 써 봄.
/*    
   int n;
   int s;
   int k;
   for (n=0; n<20; n++){
       s = number[n];
       for(i=n; i<20; i++){
           if(s>number[i]){
               k = s;
               s = number[i];
               number[i] = k;
           }
        number[n] = s;
       cout << number[n] << " : ";
       }        
   }
   for (i=0; i<20; i++)
   cout << number[i] << "<";
*/



 less = number[0];
    for (i=0; i<20; i++)
        if(less>number[i]){
            k = less;
            less = number[i];    
            number[i] = k;
        }
    cout << "less: " << less << endl;

    number[0] = less;
    cout << "number[0]= " << number[0] << endl;    

    less = number[1];
    for (i=1; i<20; i++)
        if(less>number[i]){
            k = less;
            less = number[i];
            number[i] = k;
        }
//    k = number[1];
    number[1] = less;
//    less = k;
    cout << "number[1]= " << number[1] << endl;
    
    
    less = number[2];
    for (i=2; i<20; i++)
        if(less>number[i]){
            k = less;
            less = number[i];
            number[i] = k;
        }
    number[2] = less;
    cout << "number[2]= " << number[2] << endl;
 
    
    less = number[3];
    for (i=3; i<20; i++)
        if(less>number[i]){
            k = less;
            less = number[i];
            number[i] = k;
        }
    number[3] = less;
    cout << "number[3]= " << number[3] << endl;

그렇다. 난 이 코드가 대단히 비효율적이라는 것 때문에 괴로웠다. 비효율적이라기보다는 하지 않아도 되는 일을 쓸데없이 시키고 있지 않은가. 처음 숙제를 시작할 때부터 알고 있었던 사실이었다. 분명 방법이 있다는 것을 느끼면서도, 무슨 수를 써도 어쩔 수 없어 결국 for 구문 아래에서 swapping을 해야 했던 이유는, index를 기준으로 접근했을 때에는 index를 swapping해야 한다고만 생각하고, element를 기준으로 접근했을 때에는 element의 value를 swapping해야 한다고만 생각했기 때문이었다. 하지만 index를 swapping하자니 for 구문 아래에서 에러가 나고, value를 찾은 다음에는 해당 index를 for 구문 밖으로 빼낼 방법이 없고. 아예 전체 index에 대한 ghost index(?) 같은 걸 만들어야 하나 해서 심지어 실행해 옮기기까지 했던 왕삽질을 거듭했다.

사고에도 시각의 맹점 같은 게 있는 것 같다. 뭔가 있다는 것을 알면서도 죽어도 그게 보이지 않는, 죽어도 그게 생각나지 않는. 결과만 나오면 뭐 하나? 내게 코딩은 수단이지 결코 목적이 아닌 것을. 학교에 온 이유는 여기까지 왔을 때, 사고의 맹점에 다달았을 때, 더 이상 혼자 힘으로는 갈 수가 없다는 것을 수없이 느꼈기 때문이었다. 이런 건 책이나 인터넷 포럼 같은 곳에 나와 있는 것도 아니다. (이 문제는 초보 예제니까 나와 있을지도 모르겠지만. 이 문제가 문제가 아니라 사고력이 문제인 것이다.) 컴퓨터 공학을 전공한 사람이나 직업 프로그래머라고 해서 실마리를 주는 것도 아니었다. 내가 뭐 그렇게 어려운 알고리듬을 원하는 것도 아니건만. (조금은 원하나? 당장이 아니라서 그렇지.) 내가 코딩해서 원하는 결과가 나왔던 40여 개의 코드 중에 정말로 기능적으로 최적이며 응용이 쉽게 만들었다고 느낀 코드는 딱 하나이다. 게다가 그 또한 내 무지에서 비롯된 착각인지도 모른다.
 
교수님 코드:
int i;
int temp;
int min_index;

for (i=0; i<Length; i++)
{
    for(j=min_index+1; j<Length; j++)
    {
        if(number[min_index] > number[j])
            min_index = j;
    }
   
    temp = number[min_index];
    number[min_index] = number[i];
    number[i] = temp;
}

진짜 이거 이렇게 풀어 줄 존재가 절실했다. 실제로 어떤 일들이 벌어지고 있는지 알고 있는 사람이 절실했다. 정확하고 세세하게 알고 있어야 진정 컨트롤할 수 있기 때문이다. 나는 조절력을 가지고 싶다. 많이도 아니다. 내 작업할 수 있는 정도로만. 내가 뭐 지형이나 지질을 파악한댔나, 단지 내가 지도에서 어느 위치에 있는지만 알 수 있으면 만족이다. 초보만 떼면 되는데.

   

'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

week 3 review  (0) 2008.03.22
[Steve Oualline] 5. Arrays, Qualifiers, and Reading Numbers  (0) 2008.03.16
week 2 review  (0) 2008.03.15
[Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
hw1  (0) 2008.03.10
posted by maetel
1. swapping
지난 (주어진 데이터 - 수열 - 에서 최대값과 최소값을 구하는) 숙제로 assignment에 대해 완전히 이해했다고 생각했었는데 아니었다. ( ..)^
Swapping two data elements
int a, b, c;
a=10; b=20;
How can you exchange the values of the two variables?
이 문제 정말 헤맸음. int c가 선언되어 있어서 힌트가 되었다.


2. address
중간에 방을 세 개나 비워 둔다... 왜 그럴까...? >> ㅎㅎ 비워 두는 거 아니다.
number[]와 number는 다른 거 아니었어??? > 아니다. 같은 거다.
max와 min을 먼저 만드는 것을 보면 memory는 OS가 main() 함수를 호출하기 이전에 (즉, 프로그램이 실행되기 이전에) 마련되는 것인가? > 아니구나. main() 함수에서 선언된 순서대로인 것이 맞다.

(관련 있는지 모르겠지만,)http://cplusplus.com/doc/tutorial/pointers.html
> 관련 없다.

number+i를 number로 바꾸면,
3221223080 0xbffff6a8 10
3221223080 0xbffff6a8 5
3221223080 0xbffff6a8 30
3221223080 0xbffff6a8 93
3221223080 0xbffff6a8 0
3221223080 0xbffff6a8 84
3221223080 0xbffff6a8 65
3221223080 0xbffff6a8 3
3221223080 0xbffff6a8 78
3221223080 0xbffff6a8 67
3221223080 0xbffff6a8 45
3221223080 0xbffff6a8 12
3221223080 0xbffff6a8 28
3221223080 0xbffff6a8 75
3221223080 0xbffff6a8 111
3221223080 0xbffff6a8 3
3221223080 0xbffff6a8 845
3221223080 0xbffff6a8 41
3221223080 0xbffff6a8 343
3221223080 0xbffff6a8 43
address=3221223080 (bffff6a8) = 10
address=3221223080 (bffff6a8) = 5
address=3221223080 (bffff6a8) = 30
address=3221223080 (bffff6a8) = 93
address=3221223080 (bffff6a8) = 0
address=3221223080 (bffff6a8) = 84
address=3221223080 (bffff6a8) = 65
address=3221223080 (bffff6a8) = 3
address=3221223080 (bffff6a8) = 78
address=3221223080 (bffff6a8) = 67
address=3221223080 (bffff6a8) = 45
address=3221223080 (bffff6a8) = 12
address=3221223080 (bffff6a8) = 28
address=3221223080 (bffff6a8) = 75
address=3221223080 (bffff6a8) = 111
address=3221223080 (bffff6a8) = 3
address=3221223080 (bffff6a8) = 845
address=3221223080 (bffff6a8) = 41
address=3221223080 (bffff6a8) = 343
address=3221223080 (bffff6a8) = 43
Their sum is 1981
Their max is 845
Their min is 0
Address of the variable max is 0xbffff6a0
Address of the variable min is 0xbffff6a4

sum의 address를 첨가하면,
Address of the variable sum is 0xbffff69c
그렇다면, int sum이 가장 먼저 생성된다.

쉘에서 다시 실행시키면,
3221223816 0xbffff988 10
3221223816 0xbffff988 5
3221223816 0xbffff988 30
3221223816 0xbffff988 93
3221223816 0xbffff988 0
3221223816 0xbffff988 84
3221223816 0xbffff988 65
3221223816 0xbffff988 3
3221223816 0xbffff988 78
3221223816 0xbffff988 67
3221223816 0xbffff988 45
3221223816 0xbffff988 12
3221223816 0xbffff988 28
3221223816 0xbffff988 75
3221223816 0xbffff988 111
3221223816 0xbffff988 3
3221223816 0xbffff988 845
3221223816 0xbffff988 41
3221223816 0xbffff988 343
3221223816 0xbffff988 43
address=3221223816 (bffff988) = 10
address=3221223816 (bffff988) = 5
address=3221223816 (bffff988) = 30
address=3221223816 (bffff988) = 93
address=3221223816 (bffff988) = 0
address=3221223816 (bffff988) = 84
address=3221223816 (bffff988) = 65
address=3221223816 (bffff988) = 3
address=3221223816 (bffff988) = 78
address=3221223816 (bffff988) = 67
address=3221223816 (bffff988) = 45
address=3221223816 (bffff988) = 12
address=3221223816 (bffff988) = 28
address=3221223816 (bffff988) = 75
address=3221223816 (bffff988) = 111
address=3221223816 (bffff988) = 3
address=3221223816 (bffff988) = 845
address=3221223816 (bffff988) = 41
address=3221223816 (bffff988) = 343
address=3221223816 (bffff988) = 43
Their sum is 1981
Their max is 845
Their min is 0
Address of the variable max is 0xbffff980
Address of the variable min is 0xbffff984
Address of the variable sum is 0xbffff97c

아항~ memory의 주소는 compile할 때 할당되고, update를 하더라도 기존 주소를 그대로 찾아간다. 맞나??? > 틀리다. 그냥 그렇게 보였을 뿐. (메모리를 달리 사용하고 있지 않았기 때문이었다.)
여하간, 도대체 왜! sum, max, min이 먼저 만들어지고 나서 number[]가 만들어지는 것이야??? > 변수들의 형태에 따라서 분류하여 그 순서대로 만들기 때문이란다.

뜬금없이 제일 마지막에 int why 변수를 하나 첨가해 보았더니, (Xcode 실행창)
3221223084 0xbffff6ac 10
3221223084 0xbffff6ac 5
3221223084 0xbffff6ac 30
3221223084 0xbffff6ac 93
3221223084 0xbffff6ac 0
3221223084 0xbffff6ac 84
3221223084 0xbffff6ac 65
3221223084 0xbffff6ac 3
3221223084 0xbffff6ac 78
3221223084 0xbffff6ac 67
3221223084 0xbffff6ac 45
3221223084 0xbffff6ac 12
3221223084 0xbffff6ac 28
3221223084 0xbffff6ac 75
3221223084 0xbffff6ac 111
3221223084 0xbffff6ac 3
3221223084 0xbffff6ac 845
3221223084 0xbffff6ac 41
3221223084 0xbffff6ac 343
3221223084 0xbffff6ac 43
address=3221223084 (bffff6ac) = 10
address=3221223084 (bffff6ac) = 5
address=3221223084 (bffff6ac) = 30
address=3221223084 (bffff6ac) = 93
address=3221223084 (bffff6ac) = 0
address=3221223084 (bffff6ac) = 84
address=3221223084 (bffff6ac) = 65
address=3221223084 (bffff6ac) = 3
address=3221223084 (bffff6ac) = 78
address=3221223084 (bffff6ac) = 67
address=3221223084 (bffff6ac) = 45
address=3221223084 (bffff6ac) = 12
address=3221223084 (bffff6ac) = 28
address=3221223084 (bffff6ac) = 75
address=3221223084 (bffff6ac) = 111
address=3221223084 (bffff6ac) = 3
address=3221223084 (bffff6ac) = 845
address=3221223084 (bffff6ac) = 41
address=3221223084 (bffff6ac) = 343
address=3221223084 (bffff6ac) = 43
Their sum is 1981
Their max is 845
Their min is 0
Address of the variable max is 0xbffff6a0
Address of the variable min is 0xbffff6a4
Address of the variable sum is 0xbffff69c
Address of the variable why is 0xbffff6a8

헉!!! 주소 바꾼다... 도대체 뭣이야... 점점 더 이해 안 가. ㅜㅜ
어쨌든, update 시 변경 사항이 있으면 compile 후 주소를 바꿔치기도 하는 등 각 변수에게 고정된 주소를 주는 것이 아니구나.


서 교수님:
컴파일러가 C 소스코드를 분석해서 기계어로 바꾸는데, 소스코드 전체를 들여다 보면 변수들이 여럿 나오겠지요. 단일 변수들은 단일 변수들로 배치할 것이고 어레이로 선언된 것들은 따로 배치해서 메모리를 할당하게 되어 있을 겁니다. 물론 어떤 컴파일러는 그렇지 않고 다른 방법을 사용할 수도 있습니다. 그래서,  number의 어드레스가 다른 변수들과 달리 나중의 주소를 가지게 되는 것으로 판단됩니다.

number[10] 이라고 배열 선언을 하면 컴파일러는 10개의 연속된 데이터를 위한 공간을 확보하고 그 첫번째 공간의 주소를 number 에 넣습니다. 그래서 number 는 number[0] 의 주소를 가지는 것입니다.

number[1] 은 배열에서  number[0] 다음의 값을 가지는데 그 공간의 주소값을 알고 싶으면 &number[1] 이라고 하든지 number+1  이라고 하면 됩니다.

꺼꾸로, number 에서 시작하여 두 번째 즉 number[1] 의 값을 주소로부터 얻고 싶으면 number[1] 이라고  하든지 *(number+1) 로 하여 얻을 수 있습니다.

서 교수님:
각 변수들의 실제 메모리 주소 (physical address) 는 프로그램이 실행되는 시점에서 결정됩니다. 적당한 메모리 위치에 OS 가 실행프로그램을 통째로 카피하고, CPU가 main() 의 첫 부분부터 실행하도록 합니다.  다른 프로그램들이 자주 실행되고 끝나는 상황이라면 변수들의 주소가 거의 매번 다르게 보일 것입니다. 그래서, 실제 주소를 지정하는 방법은 거의 없습니다.

서 교수님:
변수들이 몇 개가 있는지 어떤 형태인지를 컴파일러가 모두 조사한 후에 각 변수들에 필요한 메모리를 미리 할당해 둡니다.  이때는 상대적인 메모리 주소를 사용하죠. 소스코드에서는 변수들의 선언 순서가 중요합니다. 그러나, 실제로 실행되는 상황에서는 이미 필요한 모든 변수들이 메모리를 차지하고 있는 상황이 됩니다.

서 교수님:
C/C++ 프로그래밍은 컴퓨터 구조에 대해서 약간 알고 있으면 훨씬 더 쉽게 접근할 수 있습니다.



3.
교수님 강조:
문제의 풀이를 순차적인 언어로 표현할 수 있으면, 그것을 프로그래밍 언어로 바꿀 수 있다.



4.
warning: control reaches end of non-void function

무슨 뜻인가 했더니 >
It means that you have to return a value using the return statement before the end of your function. This does not apply to void functions because a void function does not return a value.
-> omission으로 함수의 return 값을 지정해 주지 않았을 때 생기는 경고였다.



5.
int *address;

int printf ( const char * format, ... );
%[flags][width][.precision][length]specifier

*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
> 난 이거 아직 이해 못 했다.



6.
address = &max;

&
2) A symbol used to precede a variable name (as in &x). Means the address of the named variable (address of x). Used to assign a value to a pointer variable.


 


posted by maetel
Practical C Programming
http://www.oreilly.com/catalog/pcp3/

Chapter 4. Basic Declarations and Expressions


Basic Program Structure


The basic elements of a program are the data declarations, functions, and comments.

main() 함수는 첫번째로 호출되는 함수이며, 이 main 함수가 다른 함수들을 직접 또는 간접으로 호출한다.

return(0);는 프로그램이 정상적으로 (Status=0) 존재했었음을 OS에게 보고하기 위해 쓰인다. : return value가 클수록 error가 심각하다는 뜻이다.



Variables
Each variable has a variable type.
A variable must be defined in a declaration statement just before the main() line at the top of a program.

http://en.wikipedia.org/wiki/Computer_numbering_formats

http://en.wikipedia.org/wiki/Signed_number_representations



Assignment statements
The general form of the assignment statement is:
variable = expression;
The = is used for assignment.



printf Function

printf

: a standard function to output our message
Print formatted data to stdout
Writes to the standard output (stdout) a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format.
The format tags follow this prototype:
%[flags][width][.precision][length]specifier

: 표준 입출력 함수- 표준 입출력 장치를 통해 데이터를 입력하거나 출력하는 기능을 갖고 있는 함수
- 표준 입출력 함수를 사용하려면 #include <stdio.h>를 기술해 줘야 한다.
[형식] printf(" 출력양식 ", 인수1,인수2...);
- 서식문자열에는 모든 문자를 사용할 수 있으며 변환문자와 제어문자를 제외하고는 화면에 그대로 출력
- 인수와 변환문자는 일대일 대응해야 하며 반드시 인수의 자료형과 문자의 자료형은 일치해야 한다.
ex) printf("%d + %d= %d\n",10,20,30);
출력결과 10+20=30


stdout
Standard output stream
: the default destination of regular output for applications. It is usually directed to the output device of the standard console (generally, the screen).

cf. library fuctions


%d
: integer conversion specification

parameter list

The general form of the printf statement is:
printf(format, expression-1, expression-2, ...);
where format is the string describing what to point.



Characters

escape character


'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

hw2  (0) 2008.03.15
week 2 review  (0) 2008.03.15
hw1  (0) 2008.03.10
Key concepts in programming: statement & expression  (1) 2008.03.09
week 1 review - keywords & file I/O  (0) 2008.03.07
posted by maetel

hw1

1. input.txt 파일에 20개의 정수를 임의로 입력하여 작성하시오.
2. 프로그램을 수정하여 입력 데이터 파일의 합을 구하는 프로그램을 작성하시오.
3. 최대값과 최소값을 구하는 루틴을 첨가하시오.


Xcode에서 프로젝트를 만들어 코딩할 경우, 파일명이나 폴더명을 함부로 바꾸면 (아마도 소유권 문제로) 실행이 되지 않을 수 있다. 이 경우 "no launchable executable present at path"라는 메시지가 뜬다.
쉘에서 "chmod +x 파일이름"을 친 이후 다시 컴파일하면 가능하다. 그러나 여전히 XCode 내부에서 실행시킬 수는 없었다.
얼마나 당황스러웠는지 새로 프로젝트를 만들 생각을 아예 못 한... 나는 초짜라 그런지 코딩은 재밌는 것 같은데 XCode 등이 토대로 하는 세계관(?? ㅡㅡ; )이나 컴퓨터 자체가 무섭다.


FileIn.open로 읽어 들일 파일은
XCode에서는 debug 폴더 안에, shell에서 실행시킬 때에는 .cpp 실행파일이 있는 폴더 안에 넣어 줘야 한다.

이번 숙제 엄청 간단한 거였는데 굉장히 오랜 시간이 걸렸다. 그 중 90%는 코딩이 아니라 인터페이스에 익숙치 않아 생긴 초삽질성 장애들. ㅡㅡ; 물론 처음에는 for 구문 안에 for 구문을 돌리는 등 헤매였지만... 아래 그 적나라한 흔적. (마음이 급하면 우선 손익은 Python에 기대게 된다.)
어쨌든 assignment라는 게 얼마나 고마운 건지 처음으로 알았다. 마구마구 업뎃이 되는구나. 그전에는 왕 무시했었는데.

list = [5,2,1,6,10,3,80]

max = list[0]

for i in range(6):
   

#for i in range(6):
###    print list[i]
##      for j in range(4):
##          if list[i] > list[j]:
           
#    if list[i+1] > list[i]:
#        mx0 = list[i+1]
##        print "mx0=", mx0
       
#        for j in range(i+1,6):
#            if mx0 < list[j+1]:
#                mx1 = list[j+1]
#                print "mx1=", mx1
                   
        
#            for k in range(j+1,6):
#                if mx1 < list[k+1]:
#                    mx2 = list[k+1]
#                    print "mx2=", mx2


#print "***"



'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

week 2 review  (0) 2008.03.15
[Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
Key concepts in programming: statement & expression  (1) 2008.03.09
week 1 review - keywords & file I/O  (0) 2008.03.07
vi  (0) 2008.03.07
posted by maetel

statement (문장)
- A statement will have internal components (eg, expressions).
- Many languages (e.g. C) make a distinction between statements and definitions, with a statement only containing executable code and a definition declaring an identifier.
: An instruction written in a high-level language.
- Programs consist of statements and expressions. An expression is a group of symbols that represent a value.
- Statements do not return results and are executed solely for their side effects, while expressions always return a result and often do not have side effects at all.

Simple statements

    * assignment: A := A + 1
    * call: CLEARSCREEN()
    * return: return 5;
    * goto: goto 1
    * assertion: assert(ptr != NULL);

Compound statements

    * statement block: begin WRITE('Number? '); READLN(NUMBER); end
    * if-statement: if A > 3 then WRITELN(A) else WRITELN("NOT YET") end
    * switch-statement: switch (c) { case 'a': alert(); break; case 'q': quit(); break; }
    * while-loop: while NOT EOF DO begin READLN end
    * do-loop: do { computation(&i); } while (i < 10);
    * for-loop: for A:=1 to 10 do WRITELN(A) end



expression (式)
: a combination of values, variables, operators, and functions
: any legal combination of symbols that represents a value
: 프로그래밍 작성 언어에서 어떤 값을 계산하는 숫자, 변수, 함수 호출 결과 및 이들이 연산자에 의해 조합된 것. 예를 들어 100, x, x+y, sin(y*2), y>100 등은 모두 식이다. 그 결과값의 형에 따라 산술식, 논리식, 문자열식 등이 있다.
- Each programming language and application has its own rules for what is legal and illegal.
- Every expression consists of at least one operand and can have one or more operators. Operands are values, whereas operators are symbols that represent particular actions.
- The expression is (or can be said to have) its evaluated value; the expression is a representation of that value.
-  Expressions are often classified by the type of value that they represent. For example:

# Boolean expressions : Evaluate to either TRUE or FALSE
# integer expressions: Evaluate to whole numbers, like 3 or 100
# Floating-point expressions: Evaluate to real numbers, like 3.141 or -0.005
# String expressions: Evaluate to character strings



side effect
- a function or expression is said to produce a side effect if it modifies some state in addition to returning a value.



declaration
(宣言)
- a declaration specifies a variable's dimensions, identifier, type, and other aspects. It is used to announce the existence of a variable or function.
- For variables, definitions assign bits to an area of memory that was reserved during the declaration phase. For functions, definitions supply the function body. It is thus clear that while a variable or function may be declared many times, it must only be defined once.
(1) 어떤 언어의 원시 프로그램에서 그 프로그램의 인터프리터에 필요한 정보, 특히 프로그램에서 실행 시 사용될 자료의 특성을 전달하기 위한 표현 방법.
(2) 프로그램에서 변수, 프로시저, 함수 등의 이름과 그 자료 유형, 함수의 반환값, 함수나 프로시저의 인자와 그 몸체를 정의하는 것. 특히 프로그램에서 쓰이는 변수의 형을 정의하는 것을 말한다.



ref. philphys informed:
http://en.wikibooks.org/wiki/Computer_programming#Common_concepts

http://en.wikibooks.org/wiki/Python_Programming


'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

week 2 review  (0) 2008.03.15
[Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
hw1  (0) 2008.03.10
week 1 review - keywords & file I/O  (0) 2008.03.07
vi  (0) 2008.03.07
posted by maetel

syntax
auto

break
Break is used within loops and switch statements to jump to the end of the code block. It causes the "//code..." above to be skipped and terminates the loop. In switch case statements, break causes the remaining cases to be skipped--it prevents "falling through" to other cases.
호~ 나도 이거 필요한 적 많았는데...

continue

to jump to the top of the loop block
그럼 왜 continue라고 불러??

for


goto
You cannot, for instance, jump into the middle of a function from a different function by using goto.

if



switch
The prevent falling through, include break;at the end of any code block.
신기하다!





#include
Generally, it is necessary to tell the preprocessor where to look for header files if they are not placed in the current directory or a standard system directory.

include file (짜넣기 파일)
: 복수의 프로그램이 공통으로 사용하는 정수나 영역 등에 대해서 그 속성을 뜻매김한 정보를 저장하고 있는 파일.


cout
standard output stream

standard output
The place where output goes unless you specify a different output device. The standard output device is usually the display screen.

stream
a succession of data elements made available over time

standard stream
The three I/O connections are called standard input, standard output and standard error.

사용자 삽입 이미지


console
: where text messages are shown.
: The combination of display monitor and keyboard (or other device that allows input). -> link


사용자 삽입 이미지



ifstream
Input file stream class
The file to be associated with the stream can be specified either as a parameter in the constructor or by calling member open.



File I/O

file I/O in C++
C++ has two basic classes to handle files, ifstream and ofstream. To use them, include the header file fstream. Ifstream handles file input (reading from files), and ofstream handles file output (writing to files).

file I/O in C
For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file).




질문>> main() 함수에 대하여

main() 함수란?
서 교수님:
main() 함수는 시스템 (오퍼레이팅 시스템: OS) 이 호출하는 함수이기 때문에 미리 리턴 타입을 정해 둔 것입니다. 또 이 함수의 첫번째 문장부터 수행되도록 미리 정해져 있습니다. 그래서, main() 이 없는 C 프로그램은 컴파일 에러가 나고 main() 여러 개가 있어도 에러가 나옵니다.
그리고, 좀 더 복잡한 프로그램에서는 외부 실행 파일을 직접 호출하여 사용하기도 합니다. 그런한 경우 main() 의 리턴값에 따라 수행결과를 판단할 수 있어요.

최근의 컴파일러 출력을 보면 C/C++ 의 main() 함수는 int 를 리턴하는 것으로 규정되어 있습니다. 그래서
    int main ()
이라고 선언을 하죠. 그래서, 이 함수가 끝날 때에는 항상 return return_val; 가 들어가야 합니다.  return_val은 에러가 없을 경우 통상적으로 0 을 주면 됩니다.

main() 함수 안에서 exit(0); 과 return 0; 는 같은 역할을 합니다.

컴파일할 때 아래와 같이 하면 int main() 으로 해야 된다고 경고가 나올 것입니다.
g++ V2008122-01.cpp -o V2008122-01 -Wall


main() 함수를 선언할 때 리턴 타입을 정해 주지 않으면 다음과 같은 오류 메시지가 뜬다.
/Users/lym/cintro/week1/V2008122-01.cpp:16: warning: ISO C++ forbids declaration of 'main' with no type



질문>> "int argc, char *argv[]"에 대하여

int main(int argc, char *argv[])
에서 main 다음 괄호 안의 것들은 command line argument라고 부른다.

cf. 교재 201쪽
The parameter argc is the number of arguments on the command line including the program name. The array argv contains the actual arguments.

argument
: a value that is passed to a routine
- In programming, a value that you pass to a routine. For example, if SQRT is a routine that returns the square root of a value, then SQRT(25) would return the value 5. The value 25 is the argument.
Argument
is often used synonymously with parameter, although parameter can also mean any value that can be changed. In addition, some programming languages make a distinction between arguments, which are passed in only one direction, and parameters, which can be passed back and forth, but this distinction is by no means universal.
An argument can also be an option to a command, in which case it is often called a command-line argument.

parameter
: a variable which takes on the meaning of a corresponding argument passed in a call to a subroutine.

command line argument
: argument sent to a program being called

command line


a. Xcode에서 실행시키면 다음과 같이 나오고

argc=1
argv[0]=/Users/lym/cintro/week1/build/Debug/week1
argv[1]=

b. 터미널에서 실행시키면 다음과 같이 나오고

argc=1
argv[0]=./V2008122-01
argv[1]=metelsmac:~/cintro/week1 lym$ ./V2008122-01 input.txt

c. 터미널에서 "./V2008122-01 input.txt"라고 치면 다음과 같이 나옵니다.

argc=2
argv[0]=./V2008122-01
argv[1]=input.txt
서 교수님:
main(argc, argv[])에서
argv[0] = 실행프로그램 이름; 1번째는 항상 실행프로그램의 패스/이름 이 들어갑니다.

매개변수를 터미널에서 입력하는 것은 사람이 입력하지만, 사실은 shell 프로그램이 fileio 함수를 호출할 때 매개변수로 주는 것이고, 좀 더 엄밀하게는 OS가 main 함수를 호출할 때 주는 것입니다.

나는 argv[0]라는 게 굉장히 tricky하게 느껴진다. 그럼 자기 자신을 매개변수로 갖는다는 말 아닌가? 완전... '내 이름을 불러 주오~'잖아.

아~ 교수님께서 말씀하셨던 fileio.exe가 내 경우 week1.exe이구나... 내가 새 프로젝트(week1)를 만들어서 다시 작성했기 때문에. Xcode에서는 프로젝트명으로 실행파일이 만들어지고 그것은 자동으로 Debug 폴더에 자리를 잡는다. 그러므로 다음과 같이 들어가서 치면 된다. 헤매인 끝에, 나는 week1폴더에 .cpp파일을 만들어 컴파일했으므로 V2008122-01.exe가 만들어졌던 것을 썼던 것인데. Xcode와 쉘에서의 접근 경로가 이번에도 다르다.
999:~/cintro/week1/build/Debug lym$ ./week1 input.txt
Their sum is 1969.
The maximum number is 999.
The minimum number is 1.
argc=2
argv[0]=./week1
argv[1]=input.txt





질문>> "using namespace std;"에 대하여

서 교수님:
한 개의 프로그램에서 여러 개의 동일한 이름을 가지는 함수를 사용하게 될  때namespace 라는 것을 사용하여 구분하기 쉽도록 한 것입니다.  C++ 의 한 가지 기능입니다.
그 줄 (using namespace std;) 은
#include <fstream>
#include <iostream>
이 있을 때 포함시키면 편리합니다.


(1) using namespace std; 을 사용하고 싶지 않은 경우
(2) 다른 헤더파일에서도 ifstream, cout, endl 등의 함수를 정의하고 있어서 그 함수들을 사용할 때 구별이 필요한 경우 다음과 같이 하면 됩니다.

ifstream -> std::ifstream
cout -> std::cout
endl -> std::endl



'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

week 2 review  (0) 2008.03.15
[Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
hw1  (0) 2008.03.10
Key concepts in programming: statement & expression  (1) 2008.03.09
vi  (0) 2008.03.07
posted by maetel

vi

'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

week 2 review  (0) 2008.03.15
[Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
hw1  (0) 2008.03.10
Key concepts in programming: statement & expression  (1) 2008.03.09
week 1 review - keywords & file I/O  (0) 2008.03.07
posted by maetel