0% found this document useful (0 votes)
17 views

Example For Programming in C and Notes

Uploaded by

huy.phamphuc1005
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Example For Programming in C and Notes

Uploaded by

huy.phamphuc1005
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Please write a program to copy characters from its input to its

output, replacing each string of one or more blanks with a single


blank (in C)
#include <stdio.h>

int main() {
int c;
int previous_char = EOF;

while ((c = getchar()) != EOF) {


if (c != ' ' || previous_char != ' ') {
putchar(c);
}

previous_char = c;
}

return 0;
}
The program uses the getchar() function to read characters one by one from the
standard input. It checks if the character is not a space or if it is a space but the
previous character was not a space before printing it using the putchar() function.
The loop continues until the end-of-file marker (EOF) is encountered, which
typically happens when you enter Ctrl+D on Unix/Linux systems or Ctrl+Z on
Windows systems to indicate the end of input.
explain your code, line by line please
Certainly! Here's a line-by-line explanation of the C program:

cSao chép mã

#include <stdio.h>
This line includes the standard input/output library ( stdio.h ) that provides functions like getchar()
and putchar() .
cSao chép mã

int main() {
int c;
int previous_char = EOF;
The program starts by defining two variables: c to store the current character being read, and
previous_char to store the previously read character. We initialize previous_char with the end-of-
file marker ( EOF ).
cSao chép mã

while ((c = getchar()) != EOF) {


This line starts a loop that reads characters from the standard input using the getchar() function. It
assigns the value returned by getchar() to c and continues looping as long as the read character is
not the end-of-file marker ( EOF ).
cSao chép mã

if (c != ' ' || previous_char != ' ') {


putchar(c);
}
Inside the loop, we check if the current character ( c ) is not a space or if it is a space but the previous
character ( previous_char ) was not a space. If either condition is true, we print the current character
using the putchar() function.
cSao chép mã

previous_char = c;
}
Before moving on to the next iteration of the loop, we update previous_char with the value of the
current character c , so we can compare it in the next iteration.
cSao chép mã

return 0;
}
Finally, the program ends by returning 0 from the main() function, indicating successful execution.

------------------------------------------------
please write a program to print a histogram of the lengths of words
in its input with vertical bars in c programming language.

#include <stdio.h>

#define MAX_LENGTH 20 // Maximum length of words to consider

int main() {
int counts[MAX_LENGTH] = {0}; // Array to store the count of words of each length

printf("Enter some text (press Ctrl+D/Ctrl+Z to end):\n");

// Read input
char word[MAX_LENGTH];
while (scanf("%s", word) != EOF) {
int length = 0;
for (int i = 0; word[i] != '\0'; i++) {
length++;
}

if (length < MAX_LENGTH) {


counts[length]++;
}
}

// Print histogram
printf("\nWord Length Histogram:\n");

for (int i = 1; i < MAX_LENGTH; i++) {


printf("%2d: ", i);

// Print bars
for (int j = 0; j < counts[i]; j++) {
printf("#");
}
printf("\n");
}

return 0;
}
In this program, we use an array counts to store the count of words of each length. We read
input from the user and calculate the length of each word. If the length is less than the maximum
length ( MAX_LENGTH ), we increase the count for that word length.
After reading all the input, we print the histogram by iterating over the counts array. Each line of
the histogram corresponds to a word length, and the number of hash ( # ) symbols represents the
count of words of that length.
Please note that this program assumes a maximum word length of 20 characters. Feel free to
modify the MAX_LENGTH constant according to your requirements.

explain your code line by line

Certainly! Here's an explanation of each line of code in the program:

cSao chép mã

#include <stdio.h>
This line includes the standard input/output library, which provides functions for reading and writing
data.

cSao chép mã

#define MAX_LENGTH 20 // Maximum length of words to consider


This line defines a constant MAX_LENGTH to specify the maximum length of words that will be
considered in the histogram. You can modify this value according to your requirements.
cSao chép mã

int main() {
int counts[MAX_LENGTH] = {0}; // Array to store the count of words of each length
This is the main function where the program execution starts. It declares an integer array counts ,
which will store the count of words of each length. The array is initialized with all elements set to
zero.
cSao chép mã

printf("Enter some text (press Ctrl+D/Ctrl+Z to end):\n");


This line prints a prompt message asking the user to enter some text.

cSao chép mã

char word[MAX_LENGTH];
while (scanf("%s", word) != EOF) {
Here, a character array word is declared to store each word read from the input. The program enters
a while loop that continues until the scanf function returns EOF (end-of-file), which happens when
the user presses Ctrl+D (Unix-like systems) or Ctrl+Z (Windows).
cSao chép mã

int length = 0;
for (int i = 0; word[i] != '\0'; i++) {
length++;
}
Within the loop, we calculate the length of the current word by iterating over its characters until we
reach the null character ( \0 ) that marks the end of the string. The variable length is used to store
the length of the word.
cSao chép mã

if (length < MAX_LENGTH) {


counts[length]++;
}
If the length of the word is less than MAX_LENGTH , we increment the count for that particular word
length in the counts array.
cSao chép mã

printf("\nWord Length Histogram:\n");


This line prints a header for the histogram output.

cSao chép mã

for (int i = 1; i < MAX_LENGTH; i++) {


printf("%2d: ", i);
The program enters a loop that iterates from 1 to MAX_LENGTH - 1 , printing each word length and its
corresponding histogram.
cSao chép mã

// Print bars
for (int j = 0; j < counts[i]; j++) {
printf("#");
}
printf("\n");
Within the inner loop, the program prints a hash symbol ( # ) for each word count of the current
length i . After printing all the bars for a specific length, it moves to the next line.
cSao chép mã

return 0;
}
Finally, the main function ends, and the program returns 0, indicating successful execution.

Source code for C’s <stdio.h> standard library:


---------------------------------------
00001 /*
00002 * Copyright (c) 1990 The Regents of the University of California.
00003 * All rights reserved.
00004 *
00005 * Redistribution and use in source and binary forms are permitted
00006 * provided that the above copyright notice and this paragraph are
00007 * duplicated in all such forms and that any documentation,
00008 * advertising materials, and other materials related to such
00009 * distribution and use acknowledge that the software was developed
00010 * by the University of California, Berkeley. The name of the
00011 * University may not be used to endorse or promote products derived
00012 * from this software without specific prior written permission.
00013 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY
EXPRESS OR
00014 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION,
THE IMPLIED
00015 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE.
00016 *
00017 * @(#)stdio.h 5.3 (Berkeley) 3/15/86
00018 */
00019
00020 /*
00021 * NB: to fit things in six character monocase externals, the
00022 * stdio code uses the prefix `__s' for stdio objects, typically
00023 * followed by a three-character attempt at a mnemonic.
00024 */
00025
00026 #ifndef _STDIO_H_
00027 #ifdef __cplusplus
00028 extern "C" {
00029 #endif
00030 #define _STDIO_H_
00031
00032 #define _FSTDIO /* ``function stdio'' */
00033
00034 #define __need_size_t
00035 #include <stddef.h>
00036
00037 #define __need___va_list
00038 #include <stdarg.h>
00039
00040 /*
00041 * <sys/reent.h> defines __sFILE, _fpos_t.
00042 * They must be defined there because struct _reent needs them (and we
don't
00043 * want reent.h to include this file.
00044 */
00045
00046 struct __sFile
00047 {
00048 int unused;
00049 };
00050
00051 typedef struct __sFILE FILE;
00052
00053 #define __SLBF 0x0001 /* line buffered */
00054 #define __SNBF 0x0002 /* unbuffered */
00055 #define __SRD 0x0004 /* OK to read */
00056 #define __SWR 0x0008 /* OK to write */
00057 /* RD and WR are never simultaneously asserted */
00058 #define __SRW 0x0010 /* open for reading & writing */
00059 #define __SEOF 0x0020 /* found EOF */
00060 #define __SERR 0x0040 /* found error */
00061 #define __SMBF 0x0080 /* _buf is from malloc */
00062 #define __SAPP 0x0100 /* fdopen()ed in append mode - so must
write to end */
00063 #define __SSTR 0x0200 /* this is an sprintf/snprintf string */
00064 #define __SOPT 0x0400 /* do fseek() optimisation */
00065 #define __SNPT 0x0800 /* do not do fseek() optimisation */
00066 #define __SOFF 0x1000 /* set iff _offset is in fact correct */
00067 #define __SMOD 0x2000 /* true => fgetline modified _p text */
00068 #if defined(__CYGWIN__) || defined(__CYGWIN__)
00069 #define __SCLE 0x4000 /* convert line endings CR/LF <-> NL
*/
00070 #endif
00071
00072 /*
00073 * The following three definitions are for ANSI C, which took them
00074 * from System V, which stupidly took internal interface macros and
00075 * made them official arguments to setvbuf(), without renaming them.
00076 * Hence, these ugly _IOxxx names are *supposed* to appear in user code.
00077 *
00078 * Although these happen to match their counterparts above, the
00079 * implementation does not rely on that (so these could be renumbered).
00080 */
00081 #define _IOFBF 0 /* setvbuf should set fully buffered */
00082 #define _IOLBF 1 /* setvbuf should set line buffered */
00083 #define _IONBF 2 /* setvbuf should set unbuffered */
00084
00085 #ifndef NULL
00086 #define NULL 0
00087 #endif
00088
00089 #define BUFSIZ 1024
00090 #define EOF (-1)
00091
00092 #define FOPEN_MAX 20 /* must be <= OPEN_MAX
<sys/syslimits.h> */
00093 #define FILENAME_MAX 1024 /* must be <= PATH_MAX
<sys/syslimits.h> */
00094 #define L_tmpnam 1024 /* XXX must be == PATH_MAX */
00095 #ifndef __STRICT_ANSI__
00096 #define P_tmpdir "/tmp"
00097 #endif
00098
00099 #ifndef SEEK_SET
00100 #define SEEK_SET 0 /* set file offset to offset */
00101 #endif
00102 #ifndef SEEK_CUR
00103 #define SEEK_CUR 1 /* set file offset to current plus offset */
00104 #endif
00105 #ifndef SEEK_END
00106 #define SEEK_END 2 /* set file offset to EOF plus offset */
00107 #endif
00108
00109 #define TMP_MAX 26
00110
00111 #define stdin (_impure_ptr->_stdin)
00112 #define stdout (_impure_ptr->_stdout)
00113 #define stderr (_impure_ptr->_stderr)
00114
00115 #define _stdin_r(x) ((x)->_stdin)
00116 #define _stdout_r(x) ((x)->_stdout)
00117 #define _stderr_r(x) ((x)->_stderr)
00118
00119 /*
00120 * Functions defined in ANSI C standard.
00121 */
00122
00123 #ifdef __GNUC__
00124 #define __VALIST __gnuc_va_list
00125 #else
00126 #define __VALIST char*
00127 #endif
00128
00129 #ifndef _EXFUN
00130 # define _EXFUN(N,P) N P
00131 #endif
00132
00133 int _EXFUN(printf, (const char *, ...));
00134 int _EXFUN(scanf, (const char *, ...));
00135 int _EXFUN(sscanf, (const char *, const char *, ...));
00136 int _EXFUN(vfprintf, (FILE *, const char *, __VALIST));
00137 int _EXFUN(vprintf, (const char *, __VALIST));
00138 int _EXFUN(vsprintf, (char *, const char *, __VALIST));
00139 int _EXFUN(vsnprintf, (char *, size_t, const char *, __VALIST));
00140 int _EXFUN(fgetc, (FILE *));
00141 char * _EXFUN(fgets, (char *, int, FILE *));
00142 int _EXFUN(fputc, (int, FILE *));
00143 int _EXFUN(fputs, (const char *, FILE *));
00144 int _EXFUN(getc, (FILE *));
00145 int _EXFUN(getchar, (void));
00146 char * _EXFUN(gets, (char *));
00147 int _EXFUN(putc, (int, FILE *));
00148 int _EXFUN(putchar, (int));
00149 int _EXFUN(puts, (const char *));
00150 int _EXFUN(ungetc, (int, FILE *));
00151 size_t _EXFUN(fread, (void *, size_t _size, size_t _n, FILE *));
00152 size_t _EXFUN(fwrite, (const void *, size_t _size, size_t _n, FILE *));
00153
00154 int _EXFUN(sprintf, (char *, const char *, ...));
00155 int _EXFUN(snprintf, (char *, size_t, const char *, ...));
00156
00157 #ifdef __cplusplus
00158 }
00159 #endif
00160 #endif /* _STDIO_H_ */
please explain the source code above line by line
--------------------------------
Code explanation:
Sure! Let's go through the source code line by line and explain each part:

Lines 1-18: These lines contain copyright and license information for the software.

Lines 20-31: This section is a preprocessor directive that guards against multiple
inclusion of the header file. It defines _STDIO_H_ if it's not already defined,
ensuring that the contents of the file are only included once.

Lines 34-35: These lines include the stddef.h header file and declare the need for
the size_t type.

Lines 37-38: These lines include the stdarg.h header file and declare the need for
the __va_list type.

Lines 46-50: The struct __sFile is defined here. This structure seems to be a
placeholder and is currently empty except for an unused integer member.

Line 51: The typedef keyword is used to define FILE as an alias for struct
__sFILE. This creates a new type called FILE which represents a file stream.

Lines 53-70: These lines define various flag constants used in the implementation
of stdio. Each flag represents a different aspect of the file stream, such as
buffering, read/write permissions, error states, etc.
Lines 81-83: These lines define macros for the buffering modes used in the
setvbuf() function. The names _IOFBF, _IOLBF, and _IONBF correspond to fully
buffered, line buffered, and unbuffered modes, respectively.

Lines 85-87: The NULL macro is defined here if it's not already defined. NULL
typically represents a null pointer.

Lines 89-98: These lines define several constants related to file I/O, such as buffer
size (BUFSIZ), end-of-file marker (EOF), maximum number of open files
(FOPEN_MAX), maximum file name length (FILENAME_MAX), and temporary
file name length (L_tmpnam).

Lines 100-107: These lines define macros for seeking positions in a file using the
SEEK_SET, SEEK_CUR, and SEEK_END values.

Line 109: The TMP_MAX constant represents the maximum number of unique
filenames that can be generated using tmpnam().

Lines 111-113: These lines define macros to access the standard input, output, and
error streams. They use an internal struct _impure_ptr to access the corresponding
streams.

Lines 115-117: These lines define macros _stdin_r(x), _stdout_r(x), and


_stderr_r(x) which are used to access the standard input, output, and error streams
through a given pointer x.

Lines 122-159: This section includes the function prototypes for several standard
I/O functions defined in the ANSI C standard. Some notable functions include
printf(), scanf(), fgetc(), fgets(), fputc(), fputs(), getc(), putchar(), gets(), putc(),
puts(), ungetc(), fread(), fwrite(), sprintf(), and snprintf().
These functions provide various I/O operations such as formatted output, input, file
reading/writing, string manipulation, etc.

Please note that this explanation provides a high-level overview of the code. For
more detailed information about specific functions or concepts, it's recommended
to refer to the appropriate documentation or consult the relevant standards.

---------------------------------------------
How to output complex numbers in c programming language ?
In C programming language, complex numbers can be represented using the complex data
type, which is available in the <complex.h> header. Here's how you can output complex
numbers in C:

1. Include the <complex.h> header at the beginning of your program:

cSao chép mã

#include <stdio.h>
#include <complex.h>

2. Declare a complex number variable and assign a value to it:

cSao chép mã

double complex z = 3.0 + 4.0 * I; // Represents the complex number 3 + 4i

3. Use the creal() and cimag() functions to extract the real and imaginary parts of the complex
number:

cSao chép mã

printf("Real part: %f\n", creal(z)); // Output: Real part: 3.000000


printf("Imaginary part: %f\n", cimag(z)); // Output: Imaginary part: 4.000000
4. If you want to output the entire complex number, including both its real and imaginary parts,
you can use the %f format specifier with creal() and cimag() within a printf() statement:

cSao chép mã

printf("Complex number: %f + %fi\n", creal(z), cimag(z)); // Output: Complex number:


3.000000 + 4.000000i
Make sure to link the math library by compiling your code with -lm flag when using complex
numbers:
shellSao chép mã

gcc program_name.c -o program_name -lm


This way, you can output complex numbers in C programming language.

Example:
#include <stdio.h>
#include <complex.h>
float complex num;
int main(){
num = 3.0 + 2.1 * I;
printf("Complex number is: %0.4f + %0.4fi\n",creal(num),cimag(num));
return 0;
}
--------------------------------
How to operate with complex number in c language ?
To operate with complex numbers in the C programming language, you can use the complex.h
library. Here's a brief explanation of how to work with complex numbers in C:
1. Include the complex.h header file:

cSao chép mã

#include <complex.h>
2. Define complex variables:

cSao chép mã

double complex z1, z2, result;

3. Assign values to complex variables:

cSao chép mã

z1 = 1.0 + 2.0 * I; // 1 + 2i
z2 = 3.0 - 4.0 * I; // 3 - 4i

4. Perform arithmetic operations on complex numbers:

cSao chép mã

result = z1 + z2; // Addition: (1 + 2i) + (3 - 4i) = 4 - 2i


result = z1 - z2; // Subtraction: (1 + 2i) - (3 - 4i) = -2 + 6i
result = z1 * z2; // Multiplication: (1 + 2i) * (3 - 4i) = 11 + 2i
result = z1 / z2; // Division: (1 + 2i) / (3 - 4i) = -0.2 + 0.4i

5. Access the real and imaginary parts of a complex number:

cSao chép mã

double realPart = creal(result); // Get real part: -0.2


double imagPart = cimag(result); // Get imaginary part: 0.4
Note: The I is the imaginary unit in C, and you can use it to represent the imaginary part of complex
numbers. Complex numbers in C have a real and an imaginary part, and arithmetic operations follow
the standard rules for complex arithmetic.
Make sure to compile your program using a C compiler that supports the complex.h library, such as
GCC with the -std=c99 or higher flag:
bashSao chép mã

gcc -std=c99 complex_operations.c -o complex_operations


Please note that complex numbers are not native types in C, but the complex.h header provides
functions and macros to work with them.

You might also like